MongoCollectionTest.php 56 KB

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