MongoCollectionTest.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use MongoDB\Driver\ReadPreference;
  4. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  5. /**
  6. * @author alcaeus <alcaeus@alcaeus.org>
  7. */
  8. class MongoCollectionTest extends TestCase
  9. {
  10. public function testSerialize()
  11. {
  12. $this->assertInternalType('string', serialize($this->getCollection()));
  13. }
  14. public function testGetNestedCollections()
  15. {
  16. $collection = $this->getCollection()->foo->bar;
  17. $this->assertSame('mongo-php-adapter.test.foo.bar', (string) $collection);
  18. }
  19. public function testCreateRecord()
  20. {
  21. $collection = $this->getCollection();
  22. $expected = [
  23. 'ok' => 1.0,
  24. 'n' => 0,
  25. 'err' => null,
  26. 'errmsg' => null,
  27. ];
  28. $document = ['foo' => 'bar'];
  29. $this->assertSame($expected, $collection->insert($document));
  30. $this->assertInstanceOf('MongoId', $document['_id']);
  31. $id = (string) $document['_id'];
  32. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  33. $this->assertSame(1, $newCollection->count());
  34. $object = $newCollection->findOne();
  35. $this->assertNotNull($object);
  36. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  37. $this->assertSame($id, (string) $object->_id);
  38. $this->assertObjectHasAttribute('foo', $object);
  39. $this->assertAttributeSame('bar', 'foo', $object);
  40. }
  41. public function testInsertInvalidData()
  42. {
  43. $this->setExpectedException('PHPUnit_Framework_Error_Warning', 'MongoCollection::insert(): expects parameter 1 to be an array or object, integer given');
  44. $document = 8;
  45. $this->getCollection()->insert($document);
  46. }
  47. public function testInsertEmptyArray()
  48. {
  49. $document = [];
  50. $this->getCollection()->insert($document);
  51. $this->assertSame(1, $this->getCollection()->count());
  52. }
  53. public function testInsertArrayWithNumericKeys()
  54. {
  55. $document = [1 => 'foo'];
  56. $this->getCollection()->insert($document);
  57. $this->assertSame(1, $this->getCollection()->count(['_id' => $document['_id']]));
  58. }
  59. public function testInsertEmptyObject()
  60. {
  61. $document = (object) [];
  62. $this->getCollection()->insert($document);
  63. $this->assertSame(1, $this->getCollection()->count());
  64. }
  65. public function testInsertObjectWithPrivateProperties()
  66. {
  67. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  68. $document = new PrivatePropertiesStub();
  69. $this->getCollection()->insert($document);
  70. }
  71. public function testInsertWithInvalidKey()
  72. {
  73. $document = ['*' => 'foo'];
  74. $this->getCollection()->insert($document);
  75. $this->assertSame(1, $this->getCollection()->count(['*' => 'foo']));
  76. }
  77. public function testInsertWithEmptyKey()
  78. {
  79. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  80. $document = ['' => 'foo'];
  81. $this->getCollection()->insert($document);
  82. }
  83. public function testInsertWithNumericKey()
  84. {
  85. $document = ['foo'];
  86. $this->getCollection()->insert($document);
  87. $this->assertSame(1, $this->getCollection()->count(['foo']));
  88. }
  89. public function testInsertDuplicate()
  90. {
  91. $collection = $this->getCollection();
  92. $collection->createIndex(['foo' => 1], ['unique' => true]);
  93. $document = ['foo' => 'bar'];
  94. $collection->insert($document);
  95. unset($document['_id']);
  96. $this->setExpectedExceptionRegExp('MongoDuplicateKeyException', '/E11000 duplicate key error .* mongo-php-adapter\.test/');
  97. $collection->insert($document);
  98. }
  99. public function testUnacknowledgedWrite()
  100. {
  101. $document = ['foo' => 'bar'];
  102. $this->assertTrue($this->getCollection()->insert($document, ['w' => 0]));
  103. }
  104. public function testInsertWriteConcernException()
  105. {
  106. $this->setExpectedException(
  107. 'MongoWriteConcernException',
  108. "cannot use 'w' > 1 when a host is not replicated"
  109. );
  110. $document = ['foo' => 'bar'];
  111. $this->getCollection()->insert($document, ['w' => 2]);
  112. }
  113. public function testInsertMany()
  114. {
  115. $expected = [
  116. 'ok' => 1.0,
  117. 'n' => 0,
  118. 'syncMillis' => 0,
  119. 'writtenTo' => null,
  120. 'err' => null,
  121. ];
  122. $documents = [
  123. ['foo' => 'bar'],
  124. ['bar' => 'foo']
  125. ];
  126. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents));
  127. foreach ($documents as $document) {
  128. $this->assertInstanceOf('MongoId', $document['_id']);
  129. }
  130. }
  131. public function testInsertManyWithNonNumericKeys()
  132. {
  133. $expected = [
  134. 'ok' => 1.0,
  135. 'n' => 0,
  136. 'syncMillis' => 0,
  137. 'writtenTo' => null,
  138. 'err' => null,
  139. ];
  140. $documents = [
  141. 'a' => ['foo' => 'bar'],
  142. 'b' => ['bar' => 'foo']
  143. ];
  144. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents));
  145. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  146. $this->assertSame(2, $newCollection->count());
  147. }
  148. public function testBatchInsertContinuesOnError()
  149. {
  150. $expected = [
  151. 'ok' => 1.0,
  152. 'n' => 0,
  153. 'syncMillis' => 0,
  154. 'writtenTo' => null,
  155. 'err' => null,
  156. ];
  157. $documents = [
  158. 8,
  159. 'b' => ['bar' => 'foo']
  160. ];
  161. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents, ['continueOnError' => true]));
  162. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  163. $this->assertSame(1, $newCollection->count());
  164. }
  165. public function testBatchInsertException()
  166. {
  167. $this->setExpectedExceptionRegExp('MongoDuplicateKeyException', '/E11000 duplicate key error .* mongo-php-adapter.test.*_id_/');
  168. $id = new \MongoId();
  169. $documents = [['_id' => $id, 'foo' => 'bar'], ['_id' => $id, 'foo' => 'bleh']];
  170. $this->getCollection()->batchInsert($documents);
  171. }
  172. public function testBatchInsertObjectWithPrivateProperties()
  173. {
  174. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  175. $documents = [new PrivatePropertiesStub()];
  176. $this->getCollection()->batchInsert($documents);
  177. }
  178. public function testBatchInsertWithInvalidKey()
  179. {
  180. $documents = [['*' => 'foo']];
  181. $this->getCollection()->batchInsert($documents);
  182. $this->assertSame(1, $this->getCollection()->count(['*' => 'foo']));
  183. }
  184. public function testBatchInsertWithEmptyKey()
  185. {
  186. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  187. $documents = [['' => 'foo']];
  188. $this->getCollection()->batchInsert($documents);
  189. }
  190. public function testBatchInsertWithNumericKey()
  191. {
  192. $documents = [['foo']];
  193. $this->getCollection()->batchInsert($documents);
  194. $this->assertSame(1, $this->getCollection()->count(['foo']));
  195. }
  196. public function testBatchInsertEmptyBatchException()
  197. {
  198. $this->setExpectedException('MongoException', 'No write ops were included in the batch');
  199. $documents = [];
  200. $this->getCollection()->batchInsert($documents, ['w' => 2]);
  201. }
  202. public function testUpdateWriteConcern()
  203. {
  204. $this->setExpectedException('MongoWriteConcernException', "cannot use 'w' > 1 when a host is not replicated");
  205. $this->getCollection()->update([], ['$set' => ['foo' => 'bar']], ['w' => 2]);
  206. }
  207. public function testUpdateOne()
  208. {
  209. $document = ['foo' => 'bar'];
  210. $this->getCollection()->insert($document);
  211. // Unset ID to re-insert
  212. unset($document['_id']);
  213. $this->getCollection()->insert($document);
  214. $expected = [
  215. 'ok' => 1.0,
  216. 'nModified' => 1,
  217. 'n' => 1,
  218. 'err' => null,
  219. 'errmsg' => null,
  220. 'updatedExisting' => true,
  221. ];
  222. $result = $this->getCollection()->update(['foo' => 'bar'], ['$set' => ['foo' => 'foo']]);
  223. $this->assertSame($expected, $result);
  224. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  225. }
  226. public function testUpdateReplaceOne()
  227. {
  228. $document = ['foo' => 'bar', 'bar' => 'foo'];
  229. $this->getCollection()->insert($document);
  230. // Unset ID to re-insert
  231. unset($document['_id']);
  232. $this->getCollection()->insert($document);
  233. $expected = [
  234. 'ok' => 1.0,
  235. 'nModified' => 1,
  236. 'n' => 1,
  237. 'err' => null,
  238. 'errmsg' => null,
  239. 'updatedExisting' => true,
  240. ];
  241. $result = $this->getCollection()->update(['foo' => 'bar'], ['foo' => 'foo']);
  242. $this->assertSame($expected, $result);
  243. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  244. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['bar' => 'foo']));
  245. }
  246. public function testUpdateReplaceMultiple()
  247. {
  248. $this->setExpectedExceptionRegExp('MongoWriteConcernException', '/multi update only works with \$ operators/', 9);
  249. $this->getCollection()->update(['foo' => 'bar'], ['foo' => 'foo'], ['multiple' => true]);
  250. }
  251. public function testUpdateDuplicate()
  252. {
  253. $collection = $this->getCollection();
  254. $collection->createIndex(['foo' => 1], ['unique' => 1]);
  255. $document = ['foo' => 'bar'];
  256. $collection->insert($document);
  257. $document = ['foo' => 'foo'];
  258. $collection->insert($document);
  259. $this->setExpectedException('MongoDuplicateKeyException');
  260. $collection->update(['foo' => 'bar'], ['$set' => ['foo' => 'foo']]);
  261. }
  262. public function testUpdateMany()
  263. {
  264. $document = ['change' => true, 'foo' => 'bar'];
  265. $this->getCollection()->insert($document);
  266. unset($document['_id']);
  267. $this->getCollection()->insert($document);
  268. $document = ['change' => true, 'foo' => 'foo'];
  269. $this->getCollection()->insert($document);
  270. $expected = [
  271. 'ok' => 1.0,
  272. 'nModified' => 2,
  273. 'n' => 3,
  274. 'err' => null,
  275. 'errmsg' => null,
  276. 'updatedExisting' => true,
  277. ];
  278. $result = $this->getCollection()->update(['change' => true], ['$set' => ['foo' => 'foo']], ['multiple' => true]);
  279. $this->assertSame($expected, $result);
  280. $this->assertSame(3, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  281. }
  282. public function testUnacknowledgedUpdate()
  283. {
  284. $document = ['foo' => 'bar'];
  285. $this->getCollection()->insert($document);
  286. unset($document['_id']);
  287. $this->getCollection()->insert($document);
  288. $this->assertTrue($this->getCollection()->update($document, ['$set' => ['foo' => 'foo']], ['w' => 0]));
  289. }
  290. public function testRemoveMultiple()
  291. {
  292. $document = ['change' => true, 'foo' => 'bar'];
  293. $this->getCollection()->insert($document);
  294. unset($document['_id']);
  295. $this->getCollection()->insert($document);
  296. $document = ['change' => true, 'foo' => 'foo'];
  297. $this->getCollection()->insert($document);
  298. $expected = [
  299. 'ok' => 1.0,
  300. 'n' => 2,
  301. 'err' => null,
  302. 'errmsg' => null,
  303. ];
  304. $result = $this->getCollection()->remove(['foo' => 'bar']);
  305. $this->assertSame($expected, $result);
  306. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count());
  307. }
  308. public function testRemoveSingle()
  309. {
  310. $document = ['change' => true, 'foo' => 'bar'];
  311. $this->getCollection()->insert($document);
  312. unset($document['_id']);
  313. $this->getCollection()->insert($document);
  314. unset($document['_id']);
  315. $this->getCollection()->insert($document);
  316. $expected = [
  317. 'ok' => 1.0,
  318. 'n' => 1,
  319. 'err' => null,
  320. 'errmsg' => null,
  321. ];
  322. $result = $this->getCollection()->remove(['foo' => 'bar'], ['justOne' => true]);
  323. $this->assertSame($expected, $result);
  324. $this->assertSame(2, $this->getCheckDatabase()->selectCollection('test')->count());
  325. }
  326. public function testRemoveUnacknowledged()
  327. {
  328. $document = ['change' => true, 'foo' => 'bar'];
  329. $this->getCollection()->insert($document);
  330. unset($document['_id']);
  331. $this->getCollection()->insert($document);
  332. unset($document['_id']);
  333. $this->getCollection()->insert($document);
  334. $this->assertTrue($this->getCollection()->remove(['foo' => 'bar'], ['w' => 0]));
  335. }
  336. public function testFindReturnsCursor()
  337. {
  338. $this->prepareData();
  339. $collection = $this->getCollection();
  340. $this->assertInstanceOf('MongoCursor', $collection->find());
  341. }
  342. public function testFindWithProjection()
  343. {
  344. $document = ['foo' => 'foo', 'bar' => 'bar'];
  345. $this->getCollection()->insert($document);
  346. unset($document['_id']);
  347. $this->getCollection()->insert($document);
  348. $cursor = $this->getCollection()->find(['foo' => 'foo'], ['bar' => true]);
  349. foreach ($cursor as $document) {
  350. $this->assertCount(2, $document);
  351. $this->assertArraySubset(['bar' => 'bar'], $document);
  352. }
  353. }
  354. public function testFindWithLegacyProjection()
  355. {
  356. $document = ['foo' => 'foo', 'bar' => 'bar'];
  357. $this->getCollection()->insert($document);
  358. unset($document['_id']);
  359. $this->getCollection()->insert($document);
  360. $cursor = $this->getCollection()->find(['foo' => 'foo'], ['bar']);
  361. foreach ($cursor as $document) {
  362. $this->assertCount(2, $document);
  363. $this->assertArraySubset(['bar' => 'bar'], $document);
  364. }
  365. }
  366. public function testCount()
  367. {
  368. $this->prepareData();
  369. $collection = $this->getCollection();
  370. $this->assertSame(3, $collection->count());
  371. $this->assertSame(2, $collection->count(['foo' => 'bar']));
  372. }
  373. public function testCountWithLimit()
  374. {
  375. $this->prepareData();
  376. $collection = $this->getCollection();
  377. $this->assertSame(2, $collection->count([], ['limit' => 2]));
  378. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['limit' => 1]));
  379. }
  380. public function testCountWithLimitLegacy()
  381. {
  382. $this->prepareData();
  383. $collection = $this->getCollection();
  384. $this->assertSame(2, $collection->count([], 2));
  385. $this->assertSame(1, $collection->count(['foo' => 'bar'], 1));
  386. }
  387. public function testCountWithSkip()
  388. {
  389. $this->prepareData();
  390. $collection = $this->getCollection();
  391. $this->assertSame(2, $collection->count([], ['skip' => 1]));
  392. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['skip' => 1]));
  393. }
  394. public function testCountWithSkipLegacy()
  395. {
  396. $this->prepareData();
  397. $collection = $this->getCollection();
  398. $this->assertSame(2, $collection->count([], null, 1));
  399. $this->assertSame(1, $collection->count(['foo' => 'bar'], null, 1));
  400. }
  401. public function testCountWithLimitAndSkip()
  402. {
  403. $this->prepareData();
  404. $collection = $this->getCollection();
  405. $this->assertSame(2, $collection->count([], ['skip' => 1, 'limit' => 2]));
  406. $this->assertSame(1, $collection->count([], ['skip' => 1, 'limit' => 1]));
  407. }
  408. public function testCountWithLimitAndSkipLegacy()
  409. {
  410. $this->prepareData();
  411. $collection = $this->getCollection();
  412. $this->assertSame(2, $collection->count([], 2, 1));
  413. $this->assertSame(1, $collection->count([], 1, 1));
  414. }
  415. public function testCountTimeout()
  416. {
  417. $this->failMaxTimeMS();
  418. $this->setExpectedException('MongoExecutionTimeoutException');
  419. $this->getCollection()->count([], ['maxTimeMS' => 1]);
  420. }
  421. public function testFindOne()
  422. {
  423. $this->prepareData();
  424. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  425. $this->assertSame(['foo' => 'foo'], $document);
  426. }
  427. public function testFindOneWithProjection()
  428. {
  429. $document = ['foo' => 'foo', 'bar' => 'bar'];
  430. $this->getCollection()->insert($document);
  431. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['bar' => true]);
  432. $this->assertCount(2, $document);
  433. $this->assertArraySubset(['bar' => 'bar'], $document);
  434. }
  435. public function testFindOneWithLegacyProjection()
  436. {
  437. $document = ['foo' => 'foo', 'bar' => 'bar'];
  438. $this->getCollection()->insert($document);
  439. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['bar']);
  440. $this->assertCount(2, $document);
  441. $this->assertArraySubset(['bar' => 'bar'], $document);
  442. }
  443. public function testFindOneNotFound()
  444. {
  445. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  446. $this->assertNull($document);
  447. }
  448. public function testFindOneConnectionIssue()
  449. {
  450. $this->setExpectedException('MongoConnectionException');
  451. $client = $this->getClient([], 'mongodb://localhost:28888?connectTimeoutMS=1');
  452. $collection = $client->selectCollection('mongo-php-adapter', 'test');
  453. $collection->findOne();
  454. }
  455. public function testDistinct()
  456. {
  457. $this->prepareData();
  458. $values = $this->getCollection()->distinct('foo');
  459. $this->assertInternalType('array', $values);
  460. sort($values);
  461. $this->assertEquals(['bar', 'foo'], $values);
  462. }
  463. public function testDistinctWithQuery()
  464. {
  465. $this->prepareData();
  466. $values = $this->getCollection()->distinct('foo', ['foo' => 'bar']);
  467. $this->assertInternalType('array', $values);
  468. $this->assertEquals(['bar'], $values);
  469. }
  470. public function testDistinctWithIdQuery()
  471. {
  472. $document1 = ['foo' => 'bar'];
  473. $document2 = ['foo' => 'bar'];
  474. $document3 = ['foo' => 'foo'];
  475. $collection = $this->getCollection();
  476. $collection->insert($document1);
  477. $collection->insert($document2);
  478. $collection->insert($document3);
  479. $this->assertSame(
  480. ['bar'],
  481. $collection->distinct('foo', ['_id' => [
  482. '$in' => [$document1['_id'], $document2['_id']]
  483. ]])
  484. );
  485. $this->assertEquals(
  486. ['bar', 'foo'],
  487. $collection->distinct('foo', ['_id' => [
  488. '$in' => [$document1['_id'], $document3['_id']]
  489. ]])
  490. );
  491. }
  492. public function testAggregate()
  493. {
  494. $collection = $this->getCollection();
  495. $this->prepareData();
  496. $pipeline = [
  497. [
  498. '$group' => [
  499. '_id' => '$foo',
  500. 'count' => [ '$sum' => 1 ],
  501. ],
  502. ],
  503. [
  504. '$sort' => ['_id' => 1]
  505. ]
  506. ];
  507. $result = $collection->aggregate($pipeline);
  508. $this->assertInternalType('array', $result);
  509. $this->assertArrayHasKey('result', $result);
  510. $this->assertEquals([
  511. ['_id' => 'bar', 'count' => 2],
  512. ['_id' => 'foo', 'count' => 1],
  513. ], $result['result']);
  514. }
  515. public function testAggregateWithMultiplePilelineOperatorsAsArguments()
  516. {
  517. $collection = $this->getCollection();
  518. $this->prepareData();
  519. try {
  520. $result = $collection->aggregate(
  521. [
  522. '$group' => [
  523. '_id' => '$foo',
  524. 'count' => [ '$sum' => 1 ],
  525. ],
  526. ],
  527. [
  528. '$sort' => ['_id' => 1]
  529. ]
  530. );
  531. } catch (\MongoResultException $ex) {
  532. $msg = 'MongoCollection::aggregate ( array $op [, array $op [, array $... ]] ) should accept variable amount of pipeline operators as argument'
  533. . "\n"
  534. . $ex;
  535. $this->fail($msg);
  536. }
  537. $this->assertInternalType('array', $result);
  538. $this->assertArrayHasKey('result', $result);
  539. $this->assertEquals([
  540. ['_id' => 'bar', 'count' => 2],
  541. ['_id' => 'foo', 'count' => 1],
  542. ], $result['result']);
  543. }
  544. public function testAggregateInvalidPipeline()
  545. {
  546. $collection = $this->getCollection();
  547. $pipeline = [
  548. [
  549. '$invalid' => []
  550. ],
  551. ];
  552. $this->setExpectedException('MongoResultException', 'Unrecognized pipeline stage name');
  553. $collection->aggregate($pipeline);
  554. }
  555. public function testAggregateTimeoutException()
  556. {
  557. $collection = $this->getCollection();
  558. $this->failMaxTimeMS();
  559. $this->setExpectedException('MongoExecutionTimeoutException');
  560. $pipeline = [
  561. [
  562. '$group' => [
  563. '_id' => '$foo',
  564. 'count' => [ '$sum' => 1 ],
  565. ],
  566. ],
  567. [
  568. '$sort' => ['_id' => 1]
  569. ]
  570. ];
  571. $collection->aggregate($pipeline, ['maxTimeMS' => 1]);
  572. }
  573. public function testAggregateCursor()
  574. {
  575. $collection = $this->getCollection();
  576. $this->prepareData();
  577. $pipeline = [
  578. [
  579. '$group' => [
  580. '_id' => '$foo',
  581. 'count' => [ '$sum' => 1 ],
  582. ],
  583. ],
  584. [
  585. '$sort' => ['_id' => 1]
  586. ]
  587. ];
  588. $cursor = $collection->aggregateCursor($pipeline);
  589. $this->assertInstanceOf('MongoCommandCursor', $cursor);
  590. $this->assertEquals([
  591. ['_id' => 'bar', 'count' => 2],
  592. ['_id' => 'foo', 'count' => 1],
  593. ], iterator_to_array($cursor));
  594. }
  595. public function testReadPreference()
  596. {
  597. $collection = $this->getCollection();
  598. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  599. $this->assertFalse($collection->getSlaveOkay());
  600. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  601. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  602. $this->assertTrue($collection->getSlaveOkay());
  603. $this->assertTrue($collection->setSlaveOkay(true));
  604. $this->assertSame(['type' => \MongoClient::RP_SECONDARY_PREFERRED, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  605. $this->assertTrue($collection->setSlaveOkay(false));
  606. $this->assertArraySubset(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  607. }
  608. public function testReadPreferenceIsSetInDriver()
  609. {
  610. $this->skipTestIf(extension_loaded('mongo'));
  611. $collection = $this->getCollection();
  612. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  613. // Only way to check whether options are passed down is through debugInfo
  614. $readPreference = $collection->getCollection()->__debugInfo()['readPreference'];
  615. $this->assertSame(ReadPreference::RP_SECONDARY, $readPreference->getMode());
  616. $this->assertSame([['a' => 'b']], $readPreference->getTagSets());
  617. }
  618. public function testReadPreferenceIsInherited()
  619. {
  620. $database = $this->getDatabase();
  621. $database->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  622. $collection = $database->selectCollection('test');
  623. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  624. }
  625. public function testWriteConcern()
  626. {
  627. $collection = $this->getCollection();
  628. $this->assertTrue($collection->setWriteConcern('majority', 100));
  629. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  630. }
  631. public function testWriteConcernIsSetInDriver()
  632. {
  633. $this->skipTestIf(extension_loaded('mongo'));
  634. $collection = $this->getCollection();
  635. $this->assertTrue($collection->setWriteConcern(2, 100));
  636. // Only way to check whether options are passed down is through debugInfo
  637. $writeConcern = $collection->getCollection()->__debugInfo()['writeConcern'];
  638. $this->assertSame(2, $writeConcern->getW());
  639. $this->assertSame(100, $writeConcern->getWtimeout());
  640. }
  641. public function testWriteConcernIsInherited()
  642. {
  643. $database = $this->getDatabase();
  644. $database->setWriteConcern('majority', 100);
  645. $collection = $database->selectCollection('test');
  646. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  647. }
  648. public function testSaveInsert()
  649. {
  650. $id = '54203e08d51d4a1f868b456e';
  651. $collection = $this->getCollection();
  652. $objectId = new \MongoId($id);
  653. $expected = [
  654. 'ok' => 1.0,
  655. 'nModified' => 0,
  656. 'n' => 1,
  657. 'err' => null,
  658. 'errmsg' => null,
  659. 'upserted' => $objectId,
  660. 'updatedExisting' => false,
  661. ];
  662. $document = ['_id' => $objectId, 'foo' => 'bar'];
  663. $this->assertEquals($expected, $collection->save($document));
  664. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  665. $this->assertSame(1, $newCollection->count());
  666. $object = $newCollection->findOne();
  667. $this->assertNotNull($object);
  668. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  669. $this->assertSame($id, (string) $object->_id);
  670. $this->assertObjectHasAttribute('foo', $object);
  671. $this->assertAttributeSame('bar', 'foo', $object);
  672. }
  673. public function testRemoveOne()
  674. {
  675. $id = '54203e08d51d4a1f868b456e';
  676. $collection = $this->getCollection();
  677. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  678. $collection->insert($document);
  679. $collection->remove(['_id' => new \MongoId($id)]);
  680. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  681. $this->assertSame(0, $newCollection->count());
  682. }
  683. public function testSaveUpdate()
  684. {
  685. $expected = [
  686. 'ok' => 1.0,
  687. 'nModified' => 1,
  688. 'n' => 1,
  689. 'err' => null,
  690. 'errmsg' => null,
  691. 'updatedExisting' => true,
  692. ];
  693. $id = '54203e08d51d4a1f868b456e';
  694. $collection = $this->getCollection();
  695. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  696. $saveDocument = ['_id' => new \MongoId($id), 'foo' => 'foo'];
  697. $collection->insert($insertDocument);
  698. $this->assertSame($expected, $collection->save($saveDocument));
  699. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  700. $this->assertSame(1, $newCollection->count());
  701. $object = $newCollection->findOne();
  702. $this->assertNotNull($object);
  703. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  704. $this->assertSame($id, (string) $object->_id);
  705. $this->assertObjectHasAttribute('foo', $object);
  706. $this->assertAttributeSame('foo', 'foo', $object);
  707. }
  708. public function testSavingShouldReplaceTheWholeDocument() {
  709. $id = '54203e08d51d4a1f868b456e';
  710. $collection = $this->getCollection();
  711. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  712. $saveDocument = ['_id' => new \MongoId($id)];
  713. $collection->insert($insertDocument);
  714. $collection->save($saveDocument);
  715. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  716. $this->assertSame(1, $newCollection->count());
  717. $object = $newCollection->findOne();
  718. $this->assertNotNull($object);
  719. $this->assertObjectNotHasAttribute('foo', $object);
  720. }
  721. public function testSaveDuplicate()
  722. {
  723. $collection = $this->getCollection();
  724. $collection->createIndex(['foo' => 1], ['unique' => true]);
  725. $document = ['foo' => 'bar'];
  726. $collection->save($document);
  727. $this->setExpectedException('MongoDuplicateKeyException');
  728. unset($document['_id']);
  729. $collection->save($document);
  730. }
  731. public function testSaveEmptyKeys()
  732. {
  733. $document = [];
  734. $this->getCollection()->save($document);
  735. $this->assertSame(1, $this->getCollection()->count());
  736. }
  737. public function testSaveEmptyObject()
  738. {
  739. $document = (object) [];
  740. $this->getCollection()->save($document);
  741. $this->assertSame(1, $this->getCollection()->count());
  742. }
  743. public function testGetDBRef()
  744. {
  745. $collection = $this->getCollection();
  746. $insertDocument = ['_id' => 1, 'foo' => 'bar'];
  747. $collection->insert($insertDocument);
  748. $document = $collection->getDBRef([
  749. '$ref' => 'test',
  750. '$id' => 1,
  751. ]);
  752. $this->assertEquals($insertDocument, $document);
  753. }
  754. public function testCreateDBRef()
  755. {
  756. $collection = $this->getCollection();
  757. $reference = $collection->createDBRef(['_id' => 'foo']);
  758. $this->assertSame(
  759. [
  760. '$ref' => 'test',
  761. '$id' => 'foo',
  762. ],
  763. $reference
  764. );
  765. }
  766. public function testCreateIndex()
  767. {
  768. $expected = [
  769. 'createdCollectionAutomatically' => true,
  770. 'numIndexesBefore' => 1,
  771. 'numIndexesAfter' => 2,
  772. 'ok' => 1.0,
  773. ];
  774. $collection = $this->getCollection();
  775. $this->assertSame($expected, $collection->createIndex(['foo' => 1]));
  776. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  777. $iterator = $newCollection->listIndexes();
  778. $indexes = iterator_to_array($iterator);
  779. $this->assertCount(2, $indexes);
  780. $index = $indexes[1];
  781. $this->assertSame(['foo' => 1], $index->getKey());
  782. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  783. }
  784. public function testCreateIndexInvalid()
  785. {
  786. $this->setExpectedException('MongoException', 'index specification has no elements');
  787. $this->getCollection()->createIndex([]);
  788. }
  789. public function testCreateIndexTwice()
  790. {
  791. $this->getCollection()->createIndex(['foo' => 1]);
  792. $expected = [
  793. 'createdCollectionAutomatically' => false,
  794. 'numIndexesBefore' => 2,
  795. 'numIndexesAfter' => 2,
  796. 'note' => 'all indexes already exist',
  797. 'ok' => 1.0
  798. ];
  799. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  800. }
  801. public function testCreateIndexWithDeprecatedOptions()
  802. {
  803. $this->getCollection()->createIndex(['foo' => 1], ['w' => 1]);
  804. $expected = [
  805. 'createdCollectionAutomatically' => false,
  806. 'numIndexesBefore' => 2,
  807. 'numIndexesAfter' => 2,
  808. 'note' => 'all indexes already exist',
  809. 'ok' => 1.0
  810. ];
  811. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  812. }
  813. public function testCreateIndexTwiceWithSameName()
  814. {
  815. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  816. $expected = [
  817. 'createdCollectionAutomatically' => false,
  818. 'numIndexesBefore' => 2,
  819. 'numIndexesAfter' => 2,
  820. 'note' => 'all indexes already exist',
  821. 'ok' => 1.0
  822. ];
  823. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']));
  824. }
  825. public function testCreateIndexTwiceWithDifferentName()
  826. {
  827. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  828. $expected = [
  829. 'createdCollectionAutomatically' => false,
  830. 'numIndexesBefore' => 2,
  831. 'numIndexesAfter' => 2,
  832. 'note' => 'all indexes already exist',
  833. 'ok' => 1.0
  834. ];
  835. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'index_test']));
  836. }
  837. public function testCreateIndexTwiceWithDifferentOrder()
  838. {
  839. $this->getCollection()->createIndex(['foo' => 1, 'bar' => 1]);
  840. $expected = [
  841. 'createdCollectionAutomatically' => false,
  842. 'numIndexesBefore' => 2,
  843. 'numIndexesAfter' => 3,
  844. 'ok' => 1.0
  845. ];
  846. $this->assertSame($expected, $this->getCollection()->createIndex(['bar' => 1, 'foo' => 1]));
  847. }
  848. public function testCreateIndexesWithDifferentOptions()
  849. {
  850. $this->setExpectedException('MongoResultException');
  851. $this->getCollection()->createIndex(['foo' => 1]);
  852. $this->getCollection()->createIndex(['foo' => 1], ['unique' => true]);
  853. }
  854. /**
  855. * @dataProvider createIndexIgnoredOptions
  856. */
  857. public function testCreateIndexesWithIgnoredOptions($option)
  858. {
  859. $this->getCollection()->createIndex(['foo' => 1]);
  860. $expected = [
  861. 'createdCollectionAutomatically' => false,
  862. 'numIndexesBefore' => 2,
  863. 'numIndexesAfter' => 2,
  864. 'note' => 'all indexes already exist',
  865. 'ok' => 1.0
  866. ];
  867. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], [$option => true]));
  868. }
  869. public static function createIndexIgnoredOptions()
  870. {
  871. return [
  872. 'background' => ['background'],
  873. 'dropDups' => ['dropDups'],
  874. ];
  875. }
  876. public function testCreateIndexWithSameNameAndDifferentOptions()
  877. {
  878. $this->setExpectedException('MongoResultException');
  879. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'foo']);
  880. $this->getCollection()->createIndex(['bar' => 1], ['name' => 'foo']);
  881. }
  882. public function testEnsureIndex()
  883. {
  884. $expected = [
  885. 'createdCollectionAutomatically' => true,
  886. 'numIndexesBefore' => 1,
  887. 'numIndexesAfter' => 2,
  888. 'ok' => 1.0
  889. ];
  890. $collection = $this->getCollection();
  891. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  892. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  893. $indexes = iterator_to_array($newCollection->listIndexes());
  894. $this->assertCount(2, $indexes);
  895. $index = $indexes[1];
  896. $this->assertSame(['bar' => 1], $index->getKey());
  897. $this->assertTrue($index->isUnique());
  898. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  899. }
  900. public function testEnsureIndexAlreadyExists()
  901. {
  902. $collection = $this->getCollection();
  903. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  904. $expected = [
  905. 'createdCollectionAutomatically' => false,
  906. 'numIndexesBefore' => 2,
  907. 'numIndexesAfter' => 2,
  908. 'ok' => 1.0,
  909. 'note' => 'all indexes already exist',
  910. ];
  911. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  912. }
  913. public function testEnsureIndexAlreadyExistsWithDifferentOptions()
  914. {
  915. $collection = $this->getCollection();
  916. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  917. $this->setExpectedException('MongoResultException', 'Index with name: bar_1 already exists with different options');
  918. $collection->ensureIndex(['bar' => 1]);
  919. }
  920. public function testDeleteIndexUsingIndexName()
  921. {
  922. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  923. $newCollection->createIndex(['bar' => 1], ['name' => 'bar']);
  924. $expected = [
  925. 'nIndexesWas' => 2,
  926. 'errmsg' => 'index not found with name [bar_1]',
  927. 'ok' => 0.0,
  928. 'code' => 27,
  929. ];
  930. $this->assertEquals($expected, $this->getCollection()->deleteIndex('bar'));
  931. $this->assertCount(2, iterator_to_array($newCollection->listIndexes()));
  932. }
  933. public function testDeleteIndexUsingField()
  934. {
  935. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  936. $newCollection->createIndex(['bar' => 1]);
  937. $expected = [
  938. 'nIndexesWas' => 2,
  939. 'ok' => 1.0,
  940. ];
  941. $this->assertSame($expected, $this->getCollection()->deleteIndex('bar'));
  942. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  943. }
  944. public function testDeleteIndexUsingKeys()
  945. {
  946. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  947. $newCollection->createIndex(['bar' => 1]);
  948. $expected = [
  949. 'nIndexesWas' => 2,
  950. 'ok' => 1.0,
  951. ];
  952. $this->assertSame($expected, $this->getcollection()->deleteIndex(['bar' => 1]));
  953. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  954. }
  955. public function testDeleteIndexes()
  956. {
  957. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  958. $newCollection->createIndex(['bar' => 1]);
  959. $expected = [
  960. 'nIndexesWas' => 2,
  961. 'msg' => 'non-_id indexes dropped for collection',
  962. 'ok' => 1.0,
  963. ];
  964. $this->assertSame($expected, $this->getcollection()->deleteIndexes());
  965. $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
  966. }
  967. public function testDeleteIndexesForNonExistingCollection()
  968. {
  969. $expected = [
  970. 'ok' => 0.0,
  971. 'errmsg' => 'ns not found',
  972. 'code' => 26,
  973. ];
  974. $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
  975. }
  976. public static function dataGetIndexInfo()
  977. {
  978. return [
  979. 'plainIndex' => [
  980. 'expectedIndex' => [
  981. 'v' => 1,
  982. 'key' => ['foo' => 1],
  983. 'name' => 'foo_1',
  984. 'ns' => 'mongo-php-adapter.test',
  985. ],
  986. 'fields' => ['foo' => 1],
  987. 'options' => [],
  988. ],
  989. 'uniqueIndex' => [
  990. 'expectedIndex' => [
  991. 'v' => 1,
  992. 'key' => ['foo' => 1],
  993. 'name' => 'foo_1',
  994. 'ns' => 'mongo-php-adapter.test',
  995. 'unique' => true,
  996. ],
  997. 'fields' => ['foo' => 1],
  998. 'options' => ['unique' => true],
  999. ],
  1000. 'sparseIndex' => [
  1001. 'expectedIndex' => [
  1002. 'v' => 1,
  1003. 'key' => ['foo' => 1],
  1004. 'name' => 'foo_1',
  1005. 'ns' => 'mongo-php-adapter.test',
  1006. 'sparse' => true,
  1007. ],
  1008. 'fields' => ['foo' => 1],
  1009. 'options' => ['sparse' => true],
  1010. ],
  1011. 'ttlIndex' => [
  1012. 'expectedIndex' => [
  1013. 'v' => 1,
  1014. 'key' => ['foo' => 1],
  1015. 'name' => 'foo_1',
  1016. 'ns' => 'mongo-php-adapter.test',
  1017. 'expireAfterSeconds' => 86400,
  1018. ],
  1019. 'fields' => ['foo' => 1],
  1020. 'options' => ['expireAfterSeconds' => 86400],
  1021. ],
  1022. 'textIndex' => [
  1023. 'expectedIndex' => [
  1024. 'v' => 1,
  1025. 'key' => [
  1026. '_fts' => 'text',
  1027. '_ftsx' => 1,
  1028. ],
  1029. 'name' => 'foo_text',
  1030. 'ns' => 'mongo-php-adapter.test',
  1031. 'weights' => [
  1032. 'foo' => 1,
  1033. ],
  1034. 'default_language' => 'english',
  1035. 'language_override' => 'language',
  1036. 'textIndexVersion' => 3,
  1037. ],
  1038. 'fields' => ['foo' => 'text'],
  1039. 'options' => [],
  1040. ],
  1041. 'partialFilterExpression' => [
  1042. 'expectedIndex' => [
  1043. 'v' => 1,
  1044. 'key' => ['foo' => 1],
  1045. 'name' => 'foo_1',
  1046. 'ns' => 'mongo-php-adapter.test',
  1047. 'partialFilterExpression' => [
  1048. 'bar' => ['$gt' => 1],
  1049. ],
  1050. ],
  1051. 'fields' => ['foo' => 1],
  1052. 'options' => [
  1053. 'partialFilterExpression' => ['bar' => ['$gt' => 1]],
  1054. ],
  1055. ],
  1056. 'geoSpatial' => [
  1057. 'expectedIndex' => [
  1058. 'v' => 1,
  1059. 'key' => ['foo' => '2dsphere'],
  1060. 'name' => 'foo_2dsphere',
  1061. 'ns' => 'mongo-php-adapter.test',
  1062. '2dsphereIndexVersion' => 3,
  1063. ],
  1064. 'fields' => ['foo' => '2dsphere'],
  1065. 'options' => [],
  1066. ],
  1067. 'geoHaystack' => [
  1068. 'expectedIndex' => [
  1069. 'v' => 1,
  1070. 'key' => ['foo' => 'geoHaystack', 'bar' => 1],
  1071. 'name' => 'foo_geoHaystack_bar_1',
  1072. 'ns' => 'mongo-php-adapter.test',
  1073. 'bucketSize' => 10,
  1074. ],
  1075. 'fields' => ['foo' => 'geoHaystack', 'bar' => 1],
  1076. 'options' => ['bucketSize' => 10],
  1077. ],
  1078. ];
  1079. }
  1080. /**
  1081. * @dataProvider dataGetIndexInfo
  1082. */
  1083. public function testGetIndexInfo($expectedIndex, $fields, $options)
  1084. {
  1085. $idIndex = [
  1086. 'v' => 1,
  1087. 'key' => ['_id' => 1],
  1088. 'name' => '_id_',
  1089. 'ns' => 'mongo-php-adapter.test',
  1090. ];
  1091. $expectedIndexInfo = [$idIndex, $expectedIndex];
  1092. $collection = $this->getCollection();
  1093. $collection->createIndex($fields, $options);
  1094. $this->assertEquals(
  1095. $expectedIndexInfo,
  1096. $collection->getIndexInfo()
  1097. );
  1098. }
  1099. public function testFindAndModifyUpdate()
  1100. {
  1101. $id = '54203e08d51d4a1f868b456e';
  1102. $collection = $this->getCollection();
  1103. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1104. $collection->insert($document);
  1105. $document = $collection->findAndModify(
  1106. ['_id' => new \MongoId($id)],
  1107. ['$set' => ['foo' => 'foo']]
  1108. );
  1109. $this->assertSame('bar', $document['foo']);
  1110. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1111. $this->assertSame(1, $newCollection->count());
  1112. $object = $newCollection->findOne();
  1113. $this->assertNotNull($object);
  1114. $this->assertAttributeSame('foo', 'foo', $object);
  1115. }
  1116. public function testFindAndModifyUpdateWithUpdateOptions()
  1117. {
  1118. $id = '54203e08d51d4a1f868b456e';
  1119. $collection = $this->getCollection();
  1120. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1121. $collection->insert($document);
  1122. $document = $collection->findAndModify(
  1123. ['_id' => new \MongoId($id)],
  1124. [],
  1125. [],
  1126. [
  1127. 'update' => ['bar' => 'foo']
  1128. ]
  1129. );
  1130. $this->assertSame('bar', $document['foo']);
  1131. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1132. $this->assertSame(1, $newCollection->count());
  1133. $object = $newCollection->findOne();
  1134. $this->assertNotNull($object);
  1135. $this->assertAttributeSame('foo', 'bar', $object);
  1136. $this->assertObjectNotHasAttribute('foo', $object);
  1137. }
  1138. public function testFindAndModifyWithUpdateParamAndOption()
  1139. {
  1140. $id = '54203e08d51d4a1f868b456e';
  1141. $collection = $this->getCollection();
  1142. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1143. $collection->insert($document);
  1144. $data = ['foo' => 'foo', 'bar' => 'bar'];
  1145. $this->getCollection()->findAndModify(
  1146. ['_id' => new \MongoId($id)],
  1147. [$data],
  1148. [],
  1149. [
  1150. 'update' => ['$set' => ['foo' => 'foobar']],
  1151. 'upsert' => true,
  1152. ]
  1153. );
  1154. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1155. $this->assertSame(1, $newCollection->count());
  1156. $object = $newCollection->findOne();
  1157. $this->assertNotNull($object);
  1158. $this->assertAttributeSame('foobar', 'foo', $object);
  1159. $this->assertObjectNotHasAttribute('bar', $object);
  1160. }
  1161. public function testFindAndModifyUpdateReplace()
  1162. {
  1163. $id = '54203e08d51d4a1f868b456e';
  1164. $collection = $this->getCollection();
  1165. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1166. $collection->insert($document);
  1167. $document = $collection->findAndModify(
  1168. ['_id' => new \MongoId($id)],
  1169. ['_id' => new \MongoId($id), 'foo' => 'boo']
  1170. );
  1171. $this->assertSame('bar', $document['foo']);
  1172. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1173. $this->assertSame(1, $newCollection->count());
  1174. $object = $newCollection->findOne();
  1175. $this->assertNotNull($object);
  1176. $this->assertAttributeSame('boo', 'foo', $object);
  1177. $this->assertObjectNotHasAttribute('bar', $object);
  1178. }
  1179. public function testFindAndModifyUpdateReturnNew()
  1180. {
  1181. $id = '54203e08d51d4a1f868b456e';
  1182. $collection = $this->getCollection();
  1183. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1184. $collection->insert($document);
  1185. $document = $collection->findAndModify(
  1186. ['_id' => new \MongoId($id)],
  1187. ['$set' => ['foo' => 'foo']],
  1188. null,
  1189. ['new' => true]
  1190. );
  1191. $this->assertSame('foo', $document['foo']);
  1192. }
  1193. public function testFindAndModifyWithFields()
  1194. {
  1195. $id = '54203e08d51d4a1f868b456e';
  1196. $collection = $this->getCollection();
  1197. $document = [
  1198. '_id' => new \MongoId($id),
  1199. 'foo' => 'bar',
  1200. 'bar' => 'foo',
  1201. ];
  1202. $collection->insert($document);
  1203. $document = $collection->findAndModify(
  1204. ['_id' => new \MongoId($id)],
  1205. ['$set' => ['foo' => 'foo']],
  1206. ['foo' => true]
  1207. );
  1208. $this->assertArrayNotHasKey('bar', $document);
  1209. $this->assertArrayHasKey('foo', $document);
  1210. }
  1211. public function testGroup()
  1212. {
  1213. $collection = $this->getCollection();
  1214. $document1 = ['a' => 2];
  1215. $collection->insert($document1);
  1216. $document2 = ['b' => 5];
  1217. $collection->insert($document2);
  1218. $document3 = ['a' => 1];
  1219. $collection->insert($document3);
  1220. $keys = [];
  1221. $initial = ["count" => 0];
  1222. $reduce = "function (obj, prev) { prev.count++; }";
  1223. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  1224. $result = $collection->group($keys, $initial, $reduce, $condition);
  1225. $this->assertArraySubset(
  1226. [
  1227. 'retval' => [['count' => 1.0]],
  1228. 'count' => 1.0,
  1229. 'keys' => 1,
  1230. 'ok' => 1.0,
  1231. ],
  1232. $result
  1233. );
  1234. }
  1235. public function testMapReduce()
  1236. {
  1237. $data = array(
  1238. array(
  1239. 'username' => 'jones',
  1240. 'likes' => 20.0,
  1241. 'text' => 'Hello world!'
  1242. ),
  1243. array(
  1244. 'username' => 'bob',
  1245. 'likes' => 100.0,
  1246. 'text' => 'Hello world!'
  1247. ),
  1248. array(
  1249. 'username' => 'bob',
  1250. 'likes' => 100.0,
  1251. 'text' => 'Hello world!'
  1252. ),
  1253. );
  1254. $collection = $this->getCollection();
  1255. $collection->batchInsert($data);
  1256. $map = 'function() {
  1257. emit(this.username, { count: 1, likes: this.likes });
  1258. }';
  1259. $reduce = 'function(key, values) {
  1260. var result = {count: 0, likes: 0};
  1261. values.forEach(function(value) {
  1262. result.count += value.count;
  1263. result.likes += value.likes;
  1264. });
  1265. return result;
  1266. }';
  1267. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  1268. $command = [
  1269. 'mapreduce' => $this->getCollection()->getName(),
  1270. 'map' => new \MongoCode($map),
  1271. 'reduce' => new \MongoCode($reduce),
  1272. 'query' => (object) [],
  1273. 'out' => ['inline' => true],
  1274. 'finalize' => new \MongoCode($finalize),
  1275. ];
  1276. $result = $this->getDatabase()->command($command);
  1277. $expected = [
  1278. [
  1279. '_id' => 'bob',
  1280. 'value' => [
  1281. 'count' => 2.0,
  1282. 'likes' => 200.0,
  1283. 'test' => 'test',
  1284. ],
  1285. ],
  1286. [
  1287. '_id' => 'jones',
  1288. 'value' => [
  1289. 'count' => 1.0,
  1290. 'likes' => 20.0,
  1291. 'test' => 'test',
  1292. ],
  1293. ],
  1294. ];
  1295. $this->assertSame(1.0, $result['ok']);
  1296. $this->assertSame($expected, $result['results']);
  1297. }
  1298. public function testFindAndModifyResultException()
  1299. {
  1300. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  1301. $collection = $this->getCollection();
  1302. $this->setExpectedException('MongoResultException');
  1303. $collection->findAndModify(
  1304. array("inprogress" => false, "name" => "Next promo"),
  1305. array('$unsupportedOperator' => array("tasks" => -1)),
  1306. array("tasks" => true),
  1307. array("new" => true)
  1308. );
  1309. }
  1310. public function testFindAndModifyExceptionTimeout()
  1311. {
  1312. $this->failMaxTimeMS();
  1313. $id = '54203e08d51d4a1f868b456e';
  1314. $collection = $this->getCollection();
  1315. $this->setExpectedException('MongoExecutionTimeoutException');
  1316. $document = $collection->findAndModify(
  1317. ['_id' => new \MongoId($id)],
  1318. null,
  1319. null,
  1320. ['maxTimeMS' => 1, 'remove' => true]
  1321. );
  1322. }
  1323. public function testFindAndModifyRemove()
  1324. {
  1325. $id = '54203e08d51d4a1f868b456e';
  1326. $collection = $this->getCollection();
  1327. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1328. $collection->insert($document);
  1329. $document = $collection->findAndModify(
  1330. ['_id' => new \MongoId($id)],
  1331. null,
  1332. null,
  1333. ['remove' => true]
  1334. );
  1335. $this->assertEquals('bar', $document['foo']);
  1336. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1337. $this->assertSame(0, $newCollection->count());
  1338. }
  1339. public function testValidate()
  1340. {
  1341. $collection = $this->getCollection();
  1342. $document = ['foo' => 'bar'];
  1343. $collection->insert($document);
  1344. $result = $collection->validate();
  1345. $this->assertArraySubset(
  1346. [
  1347. 'ns' => 'mongo-php-adapter.test',
  1348. 'nrecords' => 1,
  1349. 'nIndexes' => 1,
  1350. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  1351. 'valid' => true,
  1352. 'errors' => [],
  1353. ],
  1354. $result
  1355. );
  1356. }
  1357. public function testDrop()
  1358. {
  1359. $document = ['foo' => 'bar'];
  1360. $this->getCollection()->insert($document);
  1361. $expected = [
  1362. 'ns' => (string) $this->getCollection(),
  1363. 'nIndexesWas' => 1,
  1364. 'ok' => 1.0
  1365. ];
  1366. $this->assertSame($expected, $this->getCollection()->drop());
  1367. }
  1368. public function testEmptyCollectionName()
  1369. {
  1370. $this->setExpectedException('Exception', 'Collection name cannot be empty');
  1371. new \MongoCollection($this->getDatabase(), '');
  1372. }
  1373. public function testSelectCollectionWithNullBytes()
  1374. {
  1375. $this->setExpectedException('Exception', 'Collection name cannot contain null bytes');
  1376. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  1377. }
  1378. public function testSubCollectionWithNullBytes()
  1379. {
  1380. $collection = $this->getCollection();
  1381. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1382. $this->assertSame('test', $collection->getName());
  1383. }
  1384. public function testSelectCollectionWithDatabaseObject()
  1385. {
  1386. $client = $this->getClient();
  1387. $database = $this->getDatabase($client);
  1388. $collection = $client->selectCollection($database, 'test');
  1389. $this->assertSame('mongo-php-adapter.test', (string) $collection);
  1390. }
  1391. public function testHasNextLoop()
  1392. {
  1393. $collection = $this->getCollection();
  1394. for ($i = 0; $i < 5; $i++) {
  1395. $document = ['i' => $i];
  1396. $collection->insert($document);
  1397. }
  1398. $cursor = $collection->find()->sort(['i' => 1]);
  1399. $data = [];
  1400. $i = 0;
  1401. while ($cursor->hasNext()) {
  1402. $this->assertSame($i < 5, $cursor->hasNext());
  1403. $row = $cursor->getNext();
  1404. $this->assertSame($i, $row['i']);
  1405. $data[] = $row;
  1406. $i++;
  1407. }
  1408. $this->assertCount(5, $data);
  1409. }
  1410. public function testProjectionWithBSONTypes()
  1411. {
  1412. $collection = $this->getCollection();
  1413. $id = new \MongoId();
  1414. $referencedId = new \MongoId();
  1415. $data = [
  1416. '_id' => $id,
  1417. 'loveItems' => [
  1418. [
  1419. 'sellable' => [
  1420. '$ref' => 'sellables',
  1421. '$id' => $referencedId,
  1422. ]
  1423. ],
  1424. [
  1425. 'sellable' => [
  1426. '$ref' => 'sellables',
  1427. '$id' => new \MongoId(),
  1428. ]
  1429. ]
  1430. ]
  1431. ];
  1432. $collection->insert($data);
  1433. $item = $collection->findOne(
  1434. ['_id' => $id],
  1435. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1436. );
  1437. $this->assertArrayHasKey('loveItems', $item);
  1438. $this->assertCount(1, $item['loveItems']);
  1439. $cursor = $collection->find(
  1440. ['_id' => $id],
  1441. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1442. );
  1443. $items = iterator_to_array($cursor, false);
  1444. $this->assertCount(1, $items);
  1445. $this->assertCount(1, $items[0]['loveItems']);
  1446. }
  1447. }
  1448. class PrivatePropertiesStub
  1449. {
  1450. private $foo = 'bar';
  1451. }