MongoCollectionTest.php 62 KB

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