MongoCollectionTest.php 61 KB

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