MongoCollectionTest.php 49 KB

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