MongoCollectionTest.php 59 KB

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