MongoCollectionTest.php 55 KB

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