MongoCollectionTest.php 58 KB

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