MongoCollectionTest.php 62 KB

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