MongoCollectionTest.php 59 KB

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