MongoCollectionTest.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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. try {
  479. $collection->aggregate(
  480. [
  481. '$group' => [
  482. '_id' => '$foo',
  483. 'count' => [ '$sum' => 1 ],
  484. ],
  485. ],
  486. [
  487. '$sort' => ['_id' => 1]
  488. ]
  489. );
  490. $this->assertTrue(true);
  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. }
  498. public function testAggregateInvalidPipeline()
  499. {
  500. $collection = $this->getCollection();
  501. $pipeline = [
  502. [
  503. '$invalid' => []
  504. ],
  505. ];
  506. $this->setExpectedException('MongoResultException', 'Unrecognized pipeline stage name');
  507. $collection->aggregate($pipeline);
  508. }
  509. public function testAggregateTimeoutException()
  510. {
  511. $collection = $this->getCollection();
  512. $this->failMaxTimeMS();
  513. $this->setExpectedException('MongoExecutionTimeoutException');
  514. $pipeline = [
  515. [
  516. '$group' => [
  517. '_id' => '$foo',
  518. 'count' => [ '$sum' => 1 ],
  519. ],
  520. ],
  521. [
  522. '$sort' => ['_id' => 1]
  523. ]
  524. ];
  525. $collection->aggregate($pipeline, ['maxTimeMS' => 1]);
  526. }
  527. public function testAggregateCursor()
  528. {
  529. $collection = $this->getCollection();
  530. $this->prepareData();
  531. $pipeline = [
  532. [
  533. '$group' => [
  534. '_id' => '$foo',
  535. 'count' => [ '$sum' => 1 ],
  536. ],
  537. ],
  538. [
  539. '$sort' => ['_id' => 1]
  540. ]
  541. ];
  542. $cursor = $collection->aggregateCursor($pipeline);
  543. $this->assertInstanceOf('MongoCommandCursor', $cursor);
  544. $this->assertEquals([
  545. ['_id' => 'bar', 'count' => 2],
  546. ['_id' => 'foo', 'count' => 1],
  547. ], iterator_to_array($cursor));
  548. }
  549. public function testReadPreference()
  550. {
  551. $collection = $this->getCollection();
  552. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  553. $this->assertFalse($collection->getSlaveOkay());
  554. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  555. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  556. $this->assertTrue($collection->getSlaveOkay());
  557. $this->assertTrue($collection->setSlaveOkay(true));
  558. $this->assertSame(['type' => \MongoClient::RP_SECONDARY_PREFERRED, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  559. $this->assertTrue($collection->setSlaveOkay(false));
  560. $this->assertArraySubset(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  561. }
  562. public function testReadPreferenceIsSetInDriver()
  563. {
  564. $this->skipTestIf(extension_loaded('mongo'));
  565. $collection = $this->getCollection();
  566. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  567. // Only way to check whether options are passed down is through debugInfo
  568. $readPreference = $collection->getCollection()->__debugInfo()['readPreference'];
  569. $this->assertSame(ReadPreference::RP_SECONDARY, $readPreference->getMode());
  570. $this->assertSame([['a' => 'b']], $readPreference->getTagSets());
  571. }
  572. public function testReadPreferenceIsInherited()
  573. {
  574. $database = $this->getDatabase();
  575. $database->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  576. $collection = $database->selectCollection('test');
  577. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  578. }
  579. public function testWriteConcern()
  580. {
  581. $collection = $this->getCollection();
  582. $this->assertTrue($collection->setWriteConcern('majority', 100));
  583. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  584. }
  585. public function testWriteConcernIsSetInDriver()
  586. {
  587. $this->skipTestIf(extension_loaded('mongo'));
  588. $collection = $this->getCollection();
  589. $this->assertTrue($collection->setWriteConcern(2, 100));
  590. // Only way to check whether options are passed down is through debugInfo
  591. $writeConcern = $collection->getCollection()->__debugInfo()['writeConcern'];
  592. $this->assertSame(2, $writeConcern->getW());
  593. $this->assertSame(100, $writeConcern->getWtimeout());
  594. }
  595. public function testWriteConcernIsInherited()
  596. {
  597. $database = $this->getDatabase();
  598. $database->setWriteConcern('majority', 100);
  599. $collection = $database->selectCollection('test');
  600. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  601. }
  602. public function testSaveInsert()
  603. {
  604. $id = '54203e08d51d4a1f868b456e';
  605. $collection = $this->getCollection();
  606. $objectId = new \MongoId($id);
  607. $expected = [
  608. 'ok' => 1.0,
  609. 'nModified' => 0,
  610. 'n' => 1,
  611. 'err' => null,
  612. 'errmsg' => null,
  613. 'upserted' => $objectId,
  614. 'updatedExisting' => false,
  615. ];
  616. $document = ['_id' => $objectId, 'foo' => 'bar'];
  617. $this->assertEquals($expected, $collection->save($document));
  618. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  619. $this->assertSame(1, $newCollection->count());
  620. $object = $newCollection->findOne();
  621. $this->assertNotNull($object);
  622. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  623. $this->assertSame($id, (string) $object->_id);
  624. $this->assertObjectHasAttribute('foo', $object);
  625. $this->assertAttributeSame('bar', 'foo', $object);
  626. }
  627. public function testRemoveOne()
  628. {
  629. $id = '54203e08d51d4a1f868b456e';
  630. $collection = $this->getCollection();
  631. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  632. $collection->insert($document);
  633. $collection->remove(['_id' => new \MongoId($id)]);
  634. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  635. $this->assertSame(0, $newCollection->count());
  636. }
  637. public function testSaveUpdate()
  638. {
  639. $expected = [
  640. 'ok' => 1.0,
  641. 'nModified' => 1,
  642. 'n' => 1,
  643. 'err' => null,
  644. 'errmsg' => null,
  645. 'updatedExisting' => true,
  646. ];
  647. $id = '54203e08d51d4a1f868b456e';
  648. $collection = $this->getCollection();
  649. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  650. $saveDocument = ['_id' => new \MongoId($id), 'foo' => 'foo'];
  651. $collection->insert($insertDocument);
  652. $this->assertSame($expected, $collection->save($saveDocument));
  653. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  654. $this->assertSame(1, $newCollection->count());
  655. $object = $newCollection->findOne();
  656. $this->assertNotNull($object);
  657. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  658. $this->assertSame($id, (string) $object->_id);
  659. $this->assertObjectHasAttribute('foo', $object);
  660. $this->assertAttributeSame('foo', 'foo', $object);
  661. }
  662. public function testSavingShouldReplaceTheWholeDocument() {
  663. $id = '54203e08d51d4a1f868b456e';
  664. $collection = $this->getCollection();
  665. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  666. $saveDocument = ['_id' => new \MongoId($id)];
  667. $collection->insert($insertDocument);
  668. $collection->save($saveDocument);
  669. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  670. $this->assertSame(1, $newCollection->count());
  671. $object = $newCollection->findOne();
  672. $this->assertNotNull($object);
  673. $this->assertObjectNotHasAttribute('foo', $object);
  674. }
  675. public function testSaveDuplicate()
  676. {
  677. $collection = $this->getCollection();
  678. $collection->createIndex(['foo' => 1], ['unique' => true]);
  679. $document = ['foo' => 'bar'];
  680. $collection->save($document);
  681. $this->setExpectedException('MongoDuplicateKeyException');
  682. unset($document['_id']);
  683. $collection->save($document);
  684. }
  685. public function testSaveEmptyKeys()
  686. {
  687. $document = [];
  688. $this->getCollection()->save($document);
  689. $this->assertSame(1, $this->getCollection()->count());
  690. }
  691. public function testSaveEmptyObject()
  692. {
  693. $document = (object) [];
  694. $this->getCollection()->save($document);
  695. $this->assertSame(1, $this->getCollection()->count());
  696. }
  697. public function testGetDBRef()
  698. {
  699. $collection = $this->getCollection();
  700. $insertDocument = ['_id' => 1, 'foo' => 'bar'];
  701. $collection->insert($insertDocument);
  702. $document = $collection->getDBRef([
  703. '$ref' => 'test',
  704. '$id' => 1,
  705. ]);
  706. $this->assertEquals($insertDocument, $document);
  707. }
  708. public function testCreateDBRef()
  709. {
  710. $collection = $this->getCollection();
  711. $reference = $collection->createDBRef(['_id' => 'foo']);
  712. $this->assertSame(
  713. [
  714. '$ref' => 'test',
  715. '$id' => 'foo',
  716. ],
  717. $reference
  718. );
  719. }
  720. public function testCreateIndex()
  721. {
  722. $expected = [
  723. 'createdCollectionAutomatically' => true,
  724. 'numIndexesBefore' => 1,
  725. 'numIndexesAfter' => 2,
  726. 'ok' => 1.0,
  727. ];
  728. $collection = $this->getCollection();
  729. $this->assertSame($expected, $collection->createIndex(['foo' => 1]));
  730. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  731. $iterator = $newCollection->listIndexes();
  732. $indexes = iterator_to_array($iterator);
  733. $this->assertCount(2, $indexes);
  734. $index = $indexes[1];
  735. $this->assertSame(['foo' => 1], $index->getKey());
  736. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  737. }
  738. public function testCreateIndexInvalid()
  739. {
  740. $this->setExpectedException('MongoException', 'index specification has no elements');
  741. $this->getCollection()->createIndex([]);
  742. }
  743. public function testCreateIndexTwice()
  744. {
  745. $this->getCollection()->createIndex(['foo' => 1]);
  746. $expected = [
  747. 'createdCollectionAutomatically' => false,
  748. 'numIndexesBefore' => 2,
  749. 'numIndexesAfter' => 2,
  750. 'note' => 'all indexes already exist',
  751. 'ok' => 1.0
  752. ];
  753. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  754. }
  755. public function testCreateIndexWithDeprecatedOptions()
  756. {
  757. $this->getCollection()->createIndex(['foo' => 1], ['w' => 1]);
  758. $expected = [
  759. 'createdCollectionAutomatically' => false,
  760. 'numIndexesBefore' => 2,
  761. 'numIndexesAfter' => 2,
  762. 'note' => 'all indexes already exist',
  763. 'ok' => 1.0
  764. ];
  765. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  766. }
  767. public function testCreateIndexTwiceWithSameName()
  768. {
  769. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  770. $expected = [
  771. 'createdCollectionAutomatically' => false,
  772. 'numIndexesBefore' => 2,
  773. 'numIndexesAfter' => 2,
  774. 'note' => 'all indexes already exist',
  775. 'ok' => 1.0
  776. ];
  777. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']));
  778. }
  779. public function testCreateIndexTwiceWithDifferentName()
  780. {
  781. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  782. $expected = [
  783. 'createdCollectionAutomatically' => false,
  784. 'numIndexesBefore' => 2,
  785. 'numIndexesAfter' => 2,
  786. 'note' => 'all indexes already exist',
  787. 'ok' => 1.0
  788. ];
  789. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'index_test']));
  790. }
  791. public function testCreateIndexTwiceWithDifferentOrder()
  792. {
  793. $this->getCollection()->createIndex(['foo' => 1, 'bar' => 1]);
  794. $expected = [
  795. 'createdCollectionAutomatically' => false,
  796. 'numIndexesBefore' => 2,
  797. 'numIndexesAfter' => 3,
  798. 'ok' => 1.0
  799. ];
  800. $this->assertSame($expected, $this->getCollection()->createIndex(['bar' => 1, 'foo' => 1]));
  801. }
  802. public function testCreateIndexesWithDifferentOptions()
  803. {
  804. $this->setExpectedException('MongoResultException');
  805. $this->getCollection()->createIndex(['foo' => 1]);
  806. $this->getCollection()->createIndex(['foo' => 1], ['unique' => true]);
  807. }
  808. /**
  809. * @dataProvider createIndexIgnoredOptions
  810. */
  811. public function testCreateIndexesWithIgnoredOptions($option)
  812. {
  813. $this->getCollection()->createIndex(['foo' => 1]);
  814. $expected = [
  815. 'createdCollectionAutomatically' => false,
  816. 'numIndexesBefore' => 2,
  817. 'numIndexesAfter' => 2,
  818. 'note' => 'all indexes already exist',
  819. 'ok' => 1.0
  820. ];
  821. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], [$option => true]));
  822. }
  823. public static function createIndexIgnoredOptions()
  824. {
  825. return [
  826. 'background' => ['background'],
  827. 'dropDups' => ['dropDups'],
  828. ];
  829. }
  830. public function testCreateIndexWithSameNameAndDifferentOptions()
  831. {
  832. $this->setExpectedException('MongoResultException');
  833. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'foo']);
  834. $this->getCollection()->createIndex(['bar' => 1], ['name' => 'foo']);
  835. }
  836. public function testEnsureIndex()
  837. {
  838. $expected = [
  839. 'createdCollectionAutomatically' => true,
  840. 'numIndexesBefore' => 1,
  841. 'numIndexesAfter' => 2,
  842. 'ok' => 1.0
  843. ];
  844. $collection = $this->getCollection();
  845. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  846. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  847. $indexes = iterator_to_array($newCollection->listIndexes());
  848. $this->assertCount(2, $indexes);
  849. $index = $indexes[1];
  850. $this->assertSame(['bar' => 1], $index->getKey());
  851. $this->assertTrue($index->isUnique());
  852. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  853. }
  854. public function testEnsureIndexAlreadyExists()
  855. {
  856. $collection = $this->getCollection();
  857. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  858. $expected = [
  859. 'createdCollectionAutomatically' => false,
  860. 'numIndexesBefore' => 2,
  861. 'numIndexesAfter' => 2,
  862. 'ok' => 1.0,
  863. 'note' => 'all indexes already exist',
  864. ];
  865. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  866. }
  867. public function testEnsureIndexAlreadyExistsWithDifferentOptions()
  868. {
  869. $collection = $this->getCollection();
  870. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  871. $this->setExpectedException('MongoResultException', 'Index with name: bar_1 already exists with different options');
  872. $collection->ensureIndex(['bar' => 1]);
  873. }
  874. public function testDeleteIndexUsingIndexName()
  875. {
  876. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  877. $newCollection->createIndex(['bar' => 1], ['name' => 'bar']);
  878. $expected = [
  879. 'nIndexesWas' => 2,
  880. 'errmsg' => 'index not found with name [bar_1]',
  881. 'ok' => 0.0,
  882. 'code' => 27,
  883. ];
  884. $this->assertEquals($expected, $this->getCollection()->deleteIndex('bar'));
  885. $this->assertCount(2, iterator_to_array($newCollection->listIndexes()));
  886. }
  887. public function testDeleteIndexUsingField()
  888. {
  889. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  890. $newCollection->createIndex(['bar' => 1]);
  891. $expected = [
  892. 'nIndexesWas' => 2,
  893. 'ok' => 1.0,
  894. ];
  895. $this->assertSame($expected, $this->getCollection()->deleteIndex('bar'));
  896. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  897. }
  898. public function testDeleteIndexUsingKeys()
  899. {
  900. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  901. $newCollection->createIndex(['bar' => 1]);
  902. $expected = [
  903. 'nIndexesWas' => 2,
  904. 'ok' => 1.0,
  905. ];
  906. $this->assertSame($expected, $this->getcollection()->deleteIndex(['bar' => 1]));
  907. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  908. }
  909. public function testDeleteIndexes()
  910. {
  911. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  912. $newCollection->createIndex(['bar' => 1]);
  913. $expected = [
  914. 'nIndexesWas' => 2,
  915. 'msg' => 'non-_id indexes dropped for collection',
  916. 'ok' => 1.0,
  917. ];
  918. $this->assertSame($expected, $this->getcollection()->deleteIndexes());
  919. $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
  920. }
  921. public function testDeleteIndexesForNonExistingCollection()
  922. {
  923. $expected = [
  924. 'ok' => 0.0,
  925. 'errmsg' => 'ns not found',
  926. 'code' => 26,
  927. ];
  928. $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
  929. }
  930. public function testGetIndexInfo()
  931. {
  932. $collection = $this->getCollection();
  933. $collection->createIndex(['foo' => 1]);
  934. $expected = [
  935. [
  936. 'v' => 1,
  937. 'key' => ['_id' => 1],
  938. 'name' => '_id_',
  939. 'ns' => 'mongo-php-adapter.test',
  940. ],
  941. [
  942. 'v' => 1,
  943. 'key' => ['foo' => 1],
  944. 'name' => 'foo_1',
  945. 'ns' => 'mongo-php-adapter.test',
  946. ],
  947. ];
  948. $this->assertSame(
  949. $expected,
  950. $collection->getIndexInfo()
  951. );
  952. }
  953. public function testFindAndModifyUpdate()
  954. {
  955. $id = '54203e08d51d4a1f868b456e';
  956. $collection = $this->getCollection();
  957. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  958. $collection->insert($document);
  959. $document = $collection->findAndModify(
  960. ['_id' => new \MongoId($id)],
  961. ['$set' => ['foo' => 'foo']]
  962. );
  963. $this->assertSame('bar', $document['foo']);
  964. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  965. $this->assertSame(1, $newCollection->count());
  966. $object = $newCollection->findOne();
  967. $this->assertNotNull($object);
  968. $this->assertAttributeSame('foo', 'foo', $object);
  969. }
  970. public function testFindAndModifyUpdateWithUpdateOptions()
  971. {
  972. $id = '54203e08d51d4a1f868b456e';
  973. $collection = $this->getCollection();
  974. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  975. $collection->insert($document);
  976. $document = $collection->findAndModify(
  977. ['_id' => new \MongoId($id)],
  978. [],
  979. [],
  980. [
  981. 'update' => ['bar' => 'foo']
  982. ]
  983. );
  984. $this->assertSame('bar', $document['foo']);
  985. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  986. $this->assertSame(1, $newCollection->count());
  987. $object = $newCollection->findOne();
  988. $this->assertNotNull($object);
  989. $this->assertAttributeSame('foo', 'bar', $object);
  990. $this->assertObjectNotHasAttribute('foo', $object);
  991. }
  992. public function testFindAndModifyUpdateReplace()
  993. {
  994. $id = '54203e08d51d4a1f868b456e';
  995. $collection = $this->getCollection();
  996. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  997. $collection->insert($document);
  998. $document = $collection->findAndModify(
  999. ['_id' => new \MongoId($id)],
  1000. ['_id' => new \MongoId($id), 'foo' => 'boo']
  1001. );
  1002. $this->assertSame('bar', $document['foo']);
  1003. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1004. $this->assertSame(1, $newCollection->count());
  1005. $object = $newCollection->findOne();
  1006. $this->assertNotNull($object);
  1007. $this->assertAttributeSame('boo', 'foo', $object);
  1008. $this->assertObjectNotHasAttribute('bar', $object);
  1009. }
  1010. public function testFindAndModifyUpdateReturnNew()
  1011. {
  1012. $id = '54203e08d51d4a1f868b456e';
  1013. $collection = $this->getCollection();
  1014. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1015. $collection->insert($document);
  1016. $document = $collection->findAndModify(
  1017. ['_id' => new \MongoId($id)],
  1018. ['$set' => ['foo' => 'foo']],
  1019. null,
  1020. ['new' => true]
  1021. );
  1022. $this->assertSame('foo', $document['foo']);
  1023. }
  1024. public function testFindAndModifyWithFields()
  1025. {
  1026. $id = '54203e08d51d4a1f868b456e';
  1027. $collection = $this->getCollection();
  1028. $document = [
  1029. '_id' => new \MongoId($id),
  1030. 'foo' => 'bar',
  1031. 'bar' => 'foo',
  1032. ];
  1033. $collection->insert($document);
  1034. $document = $collection->findAndModify(
  1035. ['_id' => new \MongoId($id)],
  1036. ['$set' => ['foo' => 'foo']],
  1037. ['foo' => true]
  1038. );
  1039. $this->assertArrayNotHasKey('bar', $document);
  1040. $this->assertArrayHasKey('foo', $document);
  1041. }
  1042. public function testGroup()
  1043. {
  1044. $collection = $this->getCollection();
  1045. $document1 = ['a' => 2];
  1046. $collection->insert($document1);
  1047. $document2 = ['b' => 5];
  1048. $collection->insert($document2);
  1049. $document3 = ['a' => 1];
  1050. $collection->insert($document3);
  1051. $keys = [];
  1052. $initial = ["count" => 0];
  1053. $reduce = "function (obj, prev) { prev.count++; }";
  1054. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  1055. $result = $collection->group($keys, $initial, $reduce, $condition);
  1056. $this->assertArraySubset(
  1057. [
  1058. 'retval' => [['count' => 1.0]],
  1059. 'count' => 1.0,
  1060. 'keys' => 1,
  1061. 'ok' => 1.0,
  1062. ],
  1063. $result
  1064. );
  1065. }
  1066. public function testMapReduce()
  1067. {
  1068. $data = array(
  1069. array(
  1070. 'username' => 'jones',
  1071. 'likes' => 20.0,
  1072. 'text' => 'Hello world!'
  1073. ),
  1074. array(
  1075. 'username' => 'bob',
  1076. 'likes' => 100.0,
  1077. 'text' => 'Hello world!'
  1078. ),
  1079. array(
  1080. 'username' => 'bob',
  1081. 'likes' => 100.0,
  1082. 'text' => 'Hello world!'
  1083. ),
  1084. );
  1085. $collection = $this->getCollection();
  1086. $collection->batchInsert($data);
  1087. $map = 'function() {
  1088. emit(this.username, { count: 1, likes: this.likes });
  1089. }';
  1090. $reduce = 'function(key, values) {
  1091. var result = {count: 0, likes: 0};
  1092. values.forEach(function(value) {
  1093. result.count += value.count;
  1094. result.likes += value.likes;
  1095. });
  1096. return result;
  1097. }';
  1098. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  1099. $command = [
  1100. 'mapreduce' => $this->getCollection()->getName(),
  1101. 'map' => new \MongoCode($map),
  1102. 'reduce' => new \MongoCode($reduce),
  1103. 'query' => (object) [],
  1104. 'out' => ['inline' => true],
  1105. 'finalize' => new \MongoCode($finalize),
  1106. ];
  1107. $result = $this->getDatabase()->command($command);
  1108. $expected = [
  1109. [
  1110. '_id' => 'bob',
  1111. 'value' => [
  1112. 'count' => 2.0,
  1113. 'likes' => 200.0,
  1114. 'test' => 'test',
  1115. ],
  1116. ],
  1117. [
  1118. '_id' => 'jones',
  1119. 'value' => [
  1120. 'count' => 1.0,
  1121. 'likes' => 20.0,
  1122. 'test' => 'test',
  1123. ],
  1124. ],
  1125. ];
  1126. $this->assertSame(1.0, $result['ok']);
  1127. $this->assertSame($expected, $result['results']);
  1128. }
  1129. public function testFindAndModifyResultException()
  1130. {
  1131. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  1132. $collection = $this->getCollection();
  1133. $this->setExpectedException('MongoResultException');
  1134. $collection->findAndModify(
  1135. array("inprogress" => false, "name" => "Next promo"),
  1136. array('$unsupportedOperator' => array("tasks" => -1)),
  1137. array("tasks" => true),
  1138. array("new" => true)
  1139. );
  1140. }
  1141. public function testFindAndModifyExceptionTimeout()
  1142. {
  1143. $this->failMaxTimeMS();
  1144. $id = '54203e08d51d4a1f868b456e';
  1145. $collection = $this->getCollection();
  1146. $this->setExpectedException('MongoExecutionTimeoutException');
  1147. $document = $collection->findAndModify(
  1148. ['_id' => new \MongoId($id)],
  1149. null,
  1150. null,
  1151. ['maxTimeMS' => 1, 'remove' => true]
  1152. );
  1153. }
  1154. public function testFindAndModifyRemove()
  1155. {
  1156. $id = '54203e08d51d4a1f868b456e';
  1157. $collection = $this->getCollection();
  1158. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1159. $collection->insert($document);
  1160. $document = $collection->findAndModify(
  1161. ['_id' => new \MongoId($id)],
  1162. null,
  1163. null,
  1164. ['remove' => true]
  1165. );
  1166. $this->assertEquals('bar', $document['foo']);
  1167. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1168. $this->assertSame(0, $newCollection->count());
  1169. }
  1170. public function testValidate()
  1171. {
  1172. $collection = $this->getCollection();
  1173. $document = ['foo' => 'bar'];
  1174. $collection->insert($document);
  1175. $result = $collection->validate();
  1176. $this->assertArraySubset(
  1177. [
  1178. 'ns' => 'mongo-php-adapter.test',
  1179. 'nrecords' => 1,
  1180. 'nIndexes' => 1,
  1181. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  1182. 'valid' => true,
  1183. 'errors' => [],
  1184. 'warning' => 'Some checks omitted for speed. use {full:true} option to do more thorough scan.',
  1185. 'ok' => 1.0
  1186. ],
  1187. $result
  1188. );
  1189. }
  1190. public function testDrop()
  1191. {
  1192. $document = ['foo' => 'bar'];
  1193. $this->getCollection()->insert($document);
  1194. $expected = [
  1195. 'ns' => (string) $this->getCollection(),
  1196. 'nIndexesWas' => 1,
  1197. 'ok' => 1.0
  1198. ];
  1199. $this->assertSame($expected, $this->getCollection()->drop());
  1200. }
  1201. public function testEmptyCollectionName()
  1202. {
  1203. $this->setExpectedException('Exception', 'Collection name cannot be empty');
  1204. new \MongoCollection($this->getDatabase(), '');
  1205. }
  1206. public function testSelectCollectionWithNullBytes()
  1207. {
  1208. $this->setExpectedException('Exception', 'Collection name cannot contain null bytes');
  1209. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  1210. }
  1211. public function testSubCollectionWithNullBytes()
  1212. {
  1213. $collection = $this->getCollection();
  1214. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1215. $this->assertSame('test', $collection->getName());
  1216. }
  1217. public function testSelectCollectionWithDatabaseObject()
  1218. {
  1219. $client = $this->getClient();
  1220. $database = $this->getDatabase($client);
  1221. $collection = $client->selectCollection($database, 'test');
  1222. $this->assertSame('mongo-php-adapter.test', (string) $collection);
  1223. }
  1224. public function testHasNextLoop()
  1225. {
  1226. $collection = $this->getCollection();
  1227. for ($i = 0; $i < 5; $i++) {
  1228. $document = ['i' => $i];
  1229. $collection->insert($document);
  1230. }
  1231. $cursor = $collection->find()->sort(['i' => 1]);
  1232. $data = [];
  1233. $i = 0;
  1234. while ($cursor->hasNext()) {
  1235. $this->assertSame($i < 5, $cursor->hasNext());
  1236. $row = $cursor->getNext();
  1237. $this->assertSame($i, $row['i']);
  1238. $data[] = $row;
  1239. $i++;
  1240. }
  1241. $this->assertCount(5, $data);
  1242. }
  1243. public function testProjectionWithBSONTypes()
  1244. {
  1245. $collection = $this->getCollection();
  1246. $id = new \MongoId();
  1247. $referencedId = new \MongoId();
  1248. $data = [
  1249. '_id' => $id,
  1250. 'loveItems' => [
  1251. [
  1252. 'sellable' => [
  1253. '$ref' => 'sellables',
  1254. '$id' => $referencedId,
  1255. ]
  1256. ],
  1257. [
  1258. 'sellable' => [
  1259. '$ref' => 'sellables',
  1260. '$id' => new \MongoId(),
  1261. ]
  1262. ]
  1263. ]
  1264. ];
  1265. $collection->insert($data);
  1266. $item = $collection->findOne(
  1267. ['_id' => $id],
  1268. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1269. );
  1270. $this->assertArrayHasKey('loveItems', $item);
  1271. $this->assertCount(1, $item['loveItems']);
  1272. $cursor = $collection->find(
  1273. ['_id' => $id],
  1274. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1275. );
  1276. $items = iterator_to_array($cursor, false);
  1277. $this->assertCount(1, $items);
  1278. $this->assertCount(1, $items[0]['loveItems']);
  1279. }
  1280. }
  1281. class PrivatePropertiesStub
  1282. {
  1283. private $foo = 'bar';
  1284. }