MongoCollectionTest.php 61 KB

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