MongoCollectionTest.php 61 KB

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