MongoCollectionTest.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  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 dataFindWithProjectionExcludeId
  387. */
  388. public function testFindWithProjectionExcludeId($projection)
  389. {
  390. $document = ['foo' => 'foo', 'bar' => 'bar'];
  391. $this->getCollection()->insert($document);
  392. unset($document['_id']);
  393. $this->getCollection()->insert($document);
  394. $cursor = $this->getCollection()->find(['foo' => 'foo'], $projection);
  395. foreach ($cursor as $document) {
  396. $this->assertCount(1, $document);
  397. $this->assertArrayNotHasKey('_id', $document);
  398. $this->assertArraySubset(['bar' => 'bar'], $document);
  399. }
  400. }
  401. public static function dataFindWithProjectionExcludeId()
  402. {
  403. return [
  404. 'projection' => [['_id' => false, 'bar' => true]],
  405. 'intProjection' => [['_id' => 0, 'bar' => 1]],
  406. ];
  407. }
  408. public function testCount()
  409. {
  410. $this->prepareData();
  411. $collection = $this->getCollection();
  412. $this->assertSame(3, $collection->count());
  413. $this->assertSame(2, $collection->count(['foo' => 'bar']));
  414. }
  415. public function testCountWithLimit()
  416. {
  417. $this->prepareData();
  418. $collection = $this->getCollection();
  419. $this->assertSame(2, $collection->count([], ['limit' => 2]));
  420. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['limit' => 1]));
  421. }
  422. public function testCountWithLimitLegacy()
  423. {
  424. $this->prepareData();
  425. $collection = $this->getCollection();
  426. $this->assertSame(2, $collection->count([], 2));
  427. $this->assertSame(1, $collection->count(['foo' => 'bar'], 1));
  428. }
  429. public function testCountWithSkip()
  430. {
  431. $this->prepareData();
  432. $collection = $this->getCollection();
  433. $this->assertSame(2, $collection->count([], ['skip' => 1]));
  434. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['skip' => 1]));
  435. }
  436. public function testCountWithSkipLegacy()
  437. {
  438. $this->prepareData();
  439. $collection = $this->getCollection();
  440. $this->assertSame(2, $collection->count([], null, 1));
  441. $this->assertSame(1, $collection->count(['foo' => 'bar'], null, 1));
  442. }
  443. public function testCountWithLimitAndSkip()
  444. {
  445. $this->prepareData();
  446. $collection = $this->getCollection();
  447. $this->assertSame(2, $collection->count([], ['skip' => 1, 'limit' => 2]));
  448. $this->assertSame(1, $collection->count([], ['skip' => 1, 'limit' => 1]));
  449. }
  450. public function testCountWithLimitAndSkipLegacy()
  451. {
  452. $this->prepareData();
  453. $collection = $this->getCollection();
  454. $this->assertSame(2, $collection->count([], 2, 1));
  455. $this->assertSame(1, $collection->count([], 1, 1));
  456. }
  457. public function testCountTimeout()
  458. {
  459. $this->failMaxTimeMS();
  460. $this->setExpectedException('MongoExecutionTimeoutException');
  461. $this->getCollection()->count([], ['maxTimeMS' => 1]);
  462. }
  463. public function testFindOne()
  464. {
  465. $this->prepareData();
  466. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  467. $this->assertSame(['foo' => 'foo'], $document);
  468. }
  469. public function testFindOneWithProjection()
  470. {
  471. $document = ['foo' => 'foo', 'bar' => 'bar'];
  472. $this->getCollection()->insert($document);
  473. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['bar' => true]);
  474. $this->assertCount(2, $document);
  475. $this->assertArraySubset(['bar' => 'bar'], $document);
  476. }
  477. public function testFindOneWithLegacyProjection()
  478. {
  479. $document = ['foo' => 'foo', 'bar' => 'bar'];
  480. $this->getCollection()->insert($document);
  481. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['bar']);
  482. $this->assertCount(2, $document);
  483. $this->assertArraySubset(['bar' => 'bar'], $document);
  484. }
  485. public function testFindOneNotFound()
  486. {
  487. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  488. $this->assertNull($document);
  489. }
  490. public function testFindOneConnectionIssue()
  491. {
  492. $this->setExpectedException('MongoConnectionException');
  493. $client = $this->getClient([], 'mongodb://localhost:28888?connectTimeoutMS=1');
  494. $collection = $client->selectCollection('mongo-php-adapter', 'test');
  495. $collection->findOne();
  496. }
  497. public function testDistinct()
  498. {
  499. $this->prepareData();
  500. $values = $this->getCollection()->distinct('foo');
  501. $this->assertInternalType('array', $values);
  502. sort($values);
  503. $this->assertEquals(['bar', 'foo'], $values);
  504. }
  505. public function testDistinctWithQuery()
  506. {
  507. $this->prepareData();
  508. $values = $this->getCollection()->distinct('foo', ['foo' => 'bar']);
  509. $this->assertInternalType('array', $values);
  510. $this->assertEquals(['bar'], $values);
  511. }
  512. public function testDistinctWithIdQuery()
  513. {
  514. $document1 = ['foo' => 'bar'];
  515. $document2 = ['foo' => 'bar'];
  516. $document3 = ['foo' => 'foo'];
  517. $collection = $this->getCollection();
  518. $collection->insert($document1);
  519. $collection->insert($document2);
  520. $collection->insert($document3);
  521. $this->assertSame(
  522. ['bar'],
  523. $collection->distinct('foo', ['_id' => [
  524. '$in' => [$document1['_id'], $document2['_id']]
  525. ]])
  526. );
  527. $this->assertEquals(
  528. ['bar', 'foo'],
  529. $collection->distinct('foo', ['_id' => [
  530. '$in' => [$document1['_id'], $document3['_id']]
  531. ]])
  532. );
  533. }
  534. public function testAggregate()
  535. {
  536. $collection = $this->getCollection();
  537. $this->prepareData();
  538. $pipeline = [
  539. [
  540. '$group' => [
  541. '_id' => '$foo',
  542. 'count' => [ '$sum' => 1 ],
  543. ],
  544. ],
  545. [
  546. '$sort' => ['_id' => 1]
  547. ]
  548. ];
  549. $result = $collection->aggregate($pipeline);
  550. $this->assertInternalType('array', $result);
  551. $this->assertArrayHasKey('result', $result);
  552. $this->assertEquals([
  553. ['_id' => 'bar', 'count' => 2],
  554. ['_id' => 'foo', 'count' => 1],
  555. ], $result['result']);
  556. }
  557. public function testAggregateWithMultiplePilelineOperatorsAsArguments()
  558. {
  559. $collection = $this->getCollection();
  560. $this->prepareData();
  561. try {
  562. $result = $collection->aggregate(
  563. [
  564. '$group' => [
  565. '_id' => '$foo',
  566. 'count' => [ '$sum' => 1 ],
  567. ],
  568. ],
  569. [
  570. '$sort' => ['_id' => 1]
  571. ]
  572. );
  573. } catch (\MongoResultException $ex) {
  574. $msg = 'MongoCollection::aggregate ( array $op [, array $op [, array $... ]] ) should accept variable amount of pipeline operators as argument'
  575. . "\n"
  576. . $ex;
  577. $this->fail($msg);
  578. }
  579. $this->assertInternalType('array', $result);
  580. $this->assertArrayHasKey('result', $result);
  581. $this->assertEquals([
  582. ['_id' => 'bar', 'count' => 2],
  583. ['_id' => 'foo', 'count' => 1],
  584. ], $result['result']);
  585. }
  586. public function testAggregateInvalidPipeline()
  587. {
  588. $collection = $this->getCollection();
  589. $pipeline = [
  590. [
  591. '$invalid' => []
  592. ],
  593. ];
  594. $this->setExpectedException('MongoResultException', 'Unrecognized pipeline stage name');
  595. $collection->aggregate($pipeline);
  596. }
  597. public function testAggregateTimeoutException()
  598. {
  599. $collection = $this->getCollection();
  600. $this->failMaxTimeMS();
  601. $this->setExpectedException('MongoExecutionTimeoutException');
  602. $pipeline = [
  603. [
  604. '$group' => [
  605. '_id' => '$foo',
  606. 'count' => [ '$sum' => 1 ],
  607. ],
  608. ],
  609. [
  610. '$sort' => ['_id' => 1]
  611. ]
  612. ];
  613. $collection->aggregate($pipeline, ['maxTimeMS' => 1]);
  614. }
  615. public function testAggregateCursor()
  616. {
  617. $collection = $this->getCollection();
  618. $this->prepareData();
  619. $pipeline = [
  620. [
  621. '$group' => [
  622. '_id' => '$foo',
  623. 'count' => [ '$sum' => 1 ],
  624. ],
  625. ],
  626. [
  627. '$sort' => ['_id' => 1]
  628. ]
  629. ];
  630. $cursor = $collection->aggregateCursor($pipeline);
  631. $this->assertInstanceOf('MongoCommandCursor', $cursor);
  632. $this->assertEquals([
  633. ['_id' => 'bar', 'count' => 2],
  634. ['_id' => 'foo', 'count' => 1],
  635. ], iterator_to_array($cursor));
  636. }
  637. public function testReadPreference()
  638. {
  639. $collection = $this->getCollection();
  640. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  641. $this->assertFalse($collection->getSlaveOkay());
  642. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  643. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  644. $this->assertTrue($collection->getSlaveOkay());
  645. $this->assertTrue($collection->setSlaveOkay(true));
  646. $this->assertSame(['type' => \MongoClient::RP_SECONDARY_PREFERRED, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  647. $this->assertTrue($collection->setSlaveOkay(false));
  648. $this->assertArraySubset(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  649. }
  650. public function testReadPreferenceIsSetInDriver()
  651. {
  652. $this->skipTestIf(extension_loaded('mongo'));
  653. $collection = $this->getCollection();
  654. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  655. // Only way to check whether options are passed down is through debugInfo
  656. $readPreference = $collection->getCollection()->__debugInfo()['readPreference'];
  657. $this->assertSame(ReadPreference::RP_SECONDARY, $readPreference->getMode());
  658. $this->assertSame([['a' => 'b']], $readPreference->getTagSets());
  659. }
  660. public function testReadPreferenceIsInherited()
  661. {
  662. $database = $this->getDatabase();
  663. $database->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  664. $collection = $database->selectCollection('test');
  665. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  666. }
  667. public function testWriteConcern()
  668. {
  669. $collection = $this->getCollection();
  670. $this->assertTrue($collection->setWriteConcern('majority', 100));
  671. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  672. }
  673. public function testWriteConcernIsSetInDriver()
  674. {
  675. $this->skipTestIf(extension_loaded('mongo'));
  676. $collection = $this->getCollection();
  677. $this->assertTrue($collection->setWriteConcern(2, 100));
  678. // Only way to check whether options are passed down is through debugInfo
  679. $writeConcern = $collection->getCollection()->__debugInfo()['writeConcern'];
  680. $this->assertSame(2, $writeConcern->getW());
  681. $this->assertSame(100, $writeConcern->getWtimeout());
  682. }
  683. public function testWriteConcernIsInherited()
  684. {
  685. $database = $this->getDatabase();
  686. $database->setWriteConcern('majority', 100);
  687. $collection = $database->selectCollection('test');
  688. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  689. }
  690. public function testSaveInsert()
  691. {
  692. $id = '54203e08d51d4a1f868b456e';
  693. $collection = $this->getCollection();
  694. $objectId = new \MongoId($id);
  695. $expected = [
  696. 'ok' => 1.0,
  697. 'nModified' => 0,
  698. 'n' => 1,
  699. 'err' => null,
  700. 'errmsg' => null,
  701. 'upserted' => $objectId,
  702. 'updatedExisting' => false,
  703. ];
  704. $document = ['_id' => $objectId, 'foo' => 'bar'];
  705. $this->assertEquals($expected, $collection->save($document));
  706. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  707. $this->assertSame(1, $newCollection->count());
  708. $object = $newCollection->findOne();
  709. $this->assertNotNull($object);
  710. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  711. $this->assertSame($id, (string) $object->_id);
  712. $this->assertObjectHasAttribute('foo', $object);
  713. $this->assertAttributeSame('bar', 'foo', $object);
  714. }
  715. public function testRemoveOne()
  716. {
  717. $id = '54203e08d51d4a1f868b456e';
  718. $collection = $this->getCollection();
  719. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  720. $collection->insert($document);
  721. $collection->remove(['_id' => new \MongoId($id)]);
  722. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  723. $this->assertSame(0, $newCollection->count());
  724. }
  725. public function testSaveUpdate()
  726. {
  727. $expected = [
  728. 'ok' => 1.0,
  729. 'nModified' => 1,
  730. 'n' => 1,
  731. 'err' => null,
  732. 'errmsg' => null,
  733. 'updatedExisting' => true,
  734. ];
  735. $id = '54203e08d51d4a1f868b456e';
  736. $collection = $this->getCollection();
  737. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  738. $saveDocument = ['_id' => new \MongoId($id), 'foo' => 'foo'];
  739. $collection->insert($insertDocument);
  740. $this->assertSame($expected, $collection->save($saveDocument));
  741. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  742. $this->assertSame(1, $newCollection->count());
  743. $object = $newCollection->findOne();
  744. $this->assertNotNull($object);
  745. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  746. $this->assertSame($id, (string) $object->_id);
  747. $this->assertObjectHasAttribute('foo', $object);
  748. $this->assertAttributeSame('foo', 'foo', $object);
  749. }
  750. public function testSavingShouldReplaceTheWholeDocument() {
  751. $id = '54203e08d51d4a1f868b456e';
  752. $collection = $this->getCollection();
  753. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  754. $saveDocument = ['_id' => new \MongoId($id)];
  755. $collection->insert($insertDocument);
  756. $collection->save($saveDocument);
  757. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  758. $this->assertSame(1, $newCollection->count());
  759. $object = $newCollection->findOne();
  760. $this->assertNotNull($object);
  761. $this->assertObjectNotHasAttribute('foo', $object);
  762. }
  763. public function testSaveDuplicate()
  764. {
  765. $collection = $this->getCollection();
  766. $collection->createIndex(['foo' => 1], ['unique' => true]);
  767. $document = ['foo' => 'bar'];
  768. $collection->save($document);
  769. $this->setExpectedException('MongoDuplicateKeyException');
  770. unset($document['_id']);
  771. $collection->save($document);
  772. }
  773. public function testSaveEmptyKeys()
  774. {
  775. $document = [];
  776. $this->getCollection()->save($document);
  777. $this->assertSame(1, $this->getCollection()->count());
  778. }
  779. public function testSaveEmptyObject()
  780. {
  781. $document = (object) [];
  782. $this->getCollection()->save($document);
  783. $this->assertSame(1, $this->getCollection()->count());
  784. }
  785. public function testGetDBRef()
  786. {
  787. $collection = $this->getCollection();
  788. $insertDocument = ['_id' => 1, 'foo' => 'bar'];
  789. $collection->insert($insertDocument);
  790. $document = $collection->getDBRef([
  791. '$ref' => 'test',
  792. '$id' => 1,
  793. ]);
  794. $this->assertEquals($insertDocument, $document);
  795. }
  796. public function testCreateDBRef()
  797. {
  798. $collection = $this->getCollection();
  799. $reference = $collection->createDBRef(['_id' => 'foo']);
  800. $this->assertSame(
  801. [
  802. '$ref' => 'test',
  803. '$id' => 'foo',
  804. ],
  805. $reference
  806. );
  807. }
  808. public function testCreateIndex()
  809. {
  810. $expected = [
  811. 'createdCollectionAutomatically' => true,
  812. 'numIndexesBefore' => 1,
  813. 'numIndexesAfter' => 2,
  814. 'ok' => 1.0,
  815. ];
  816. $collection = $this->getCollection();
  817. $this->assertSame($expected, $collection->createIndex(['foo' => 1]));
  818. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  819. $iterator = $newCollection->listIndexes();
  820. $indexes = iterator_to_array($iterator);
  821. $this->assertCount(2, $indexes);
  822. $index = $indexes[1];
  823. $this->assertSame(['foo' => 1], $index->getKey());
  824. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  825. }
  826. public function testCreateIndexInvalid()
  827. {
  828. $this->setExpectedException('MongoException', 'index specification has no elements');
  829. $this->getCollection()->createIndex([]);
  830. }
  831. public function testCreateIndexTwice()
  832. {
  833. $this->getCollection()->createIndex(['foo' => 1]);
  834. $expected = [
  835. 'createdCollectionAutomatically' => false,
  836. 'numIndexesBefore' => 2,
  837. 'numIndexesAfter' => 2,
  838. 'note' => 'all indexes already exist',
  839. 'ok' => 1.0
  840. ];
  841. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  842. }
  843. public function testCreateIndexWithDeprecatedOptions()
  844. {
  845. $this->getCollection()->createIndex(['foo' => 1], ['w' => 1]);
  846. $expected = [
  847. 'createdCollectionAutomatically' => false,
  848. 'numIndexesBefore' => 2,
  849. 'numIndexesAfter' => 2,
  850. 'note' => 'all indexes already exist',
  851. 'ok' => 1.0
  852. ];
  853. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  854. }
  855. public function testCreateIndexTwiceWithSameName()
  856. {
  857. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  858. $expected = [
  859. 'createdCollectionAutomatically' => false,
  860. 'numIndexesBefore' => 2,
  861. 'numIndexesAfter' => 2,
  862. 'note' => 'all indexes already exist',
  863. 'ok' => 1.0
  864. ];
  865. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']));
  866. }
  867. public function testCreateIndexTwiceWithDifferentName()
  868. {
  869. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  870. $expected = [
  871. 'createdCollectionAutomatically' => false,
  872. 'numIndexesBefore' => 2,
  873. 'numIndexesAfter' => 2,
  874. 'note' => 'all indexes already exist',
  875. 'ok' => 1.0
  876. ];
  877. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'index_test']));
  878. }
  879. public function testCreateIndexTwiceWithDifferentOrder()
  880. {
  881. $this->getCollection()->createIndex(['foo' => 1, 'bar' => 1]);
  882. $expected = [
  883. 'createdCollectionAutomatically' => false,
  884. 'numIndexesBefore' => 2,
  885. 'numIndexesAfter' => 3,
  886. 'ok' => 1.0
  887. ];
  888. $this->assertSame($expected, $this->getCollection()->createIndex(['bar' => 1, 'foo' => 1]));
  889. }
  890. public function testCreateIndexesWithDifferentOptions()
  891. {
  892. $this->setExpectedException('MongoResultException');
  893. $this->getCollection()->createIndex(['foo' => 1]);
  894. $this->getCollection()->createIndex(['foo' => 1], ['unique' => true]);
  895. }
  896. /**
  897. * @dataProvider createIndexIgnoredOptions
  898. */
  899. public function testCreateIndexesWithIgnoredOptions($option)
  900. {
  901. $this->getCollection()->createIndex(['foo' => 1]);
  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], [$option => true]));
  910. }
  911. public static function createIndexIgnoredOptions()
  912. {
  913. return [
  914. 'background' => ['background'],
  915. 'dropDups' => ['dropDups'],
  916. ];
  917. }
  918. public function testCreateIndexWithSameNameAndDifferentOptions()
  919. {
  920. $this->setExpectedException('MongoResultException');
  921. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'foo']);
  922. $this->getCollection()->createIndex(['bar' => 1], ['name' => 'foo']);
  923. }
  924. public function testEnsureIndex()
  925. {
  926. $expected = [
  927. 'createdCollectionAutomatically' => true,
  928. 'numIndexesBefore' => 1,
  929. 'numIndexesAfter' => 2,
  930. 'ok' => 1.0
  931. ];
  932. $collection = $this->getCollection();
  933. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  934. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  935. $indexes = iterator_to_array($newCollection->listIndexes());
  936. $this->assertCount(2, $indexes);
  937. $index = $indexes[1];
  938. $this->assertSame(['bar' => 1], $index->getKey());
  939. $this->assertTrue($index->isUnique());
  940. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  941. }
  942. public function testEnsureIndexAlreadyExists()
  943. {
  944. $collection = $this->getCollection();
  945. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  946. $expected = [
  947. 'createdCollectionAutomatically' => false,
  948. 'numIndexesBefore' => 2,
  949. 'numIndexesAfter' => 2,
  950. 'ok' => 1.0,
  951. 'note' => 'all indexes already exist',
  952. ];
  953. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  954. }
  955. public function testEnsureIndexAlreadyExistsWithDifferentOptions()
  956. {
  957. $collection = $this->getCollection();
  958. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  959. $this->setExpectedException('MongoResultException', 'Index with name: bar_1 already exists with different options');
  960. $collection->ensureIndex(['bar' => 1]);
  961. }
  962. public function testDeleteIndexUsingIndexName()
  963. {
  964. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  965. $newCollection->createIndex(['bar' => 1], ['name' => 'bar']);
  966. $expected = [
  967. 'nIndexesWas' => 2,
  968. 'errmsg' => 'index not found with name [bar_1]',
  969. 'ok' => 0.0,
  970. 'code' => 27,
  971. ];
  972. $this->assertEquals($expected, $this->getCollection()->deleteIndex('bar'));
  973. $this->assertCount(2, iterator_to_array($newCollection->listIndexes()));
  974. }
  975. public function testDeleteIndexUsingField()
  976. {
  977. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  978. $newCollection->createIndex(['bar' => 1]);
  979. $expected = [
  980. 'nIndexesWas' => 2,
  981. 'ok' => 1.0,
  982. ];
  983. $this->assertSame($expected, $this->getCollection()->deleteIndex('bar'));
  984. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  985. }
  986. public function testDeleteIndexUsingKeys()
  987. {
  988. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  989. $newCollection->createIndex(['bar' => 1]);
  990. $expected = [
  991. 'nIndexesWas' => 2,
  992. 'ok' => 1.0,
  993. ];
  994. $this->assertSame($expected, $this->getcollection()->deleteIndex(['bar' => 1]));
  995. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  996. }
  997. public function testDeleteIndexes()
  998. {
  999. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1000. $newCollection->createIndex(['bar' => 1]);
  1001. $expected = [
  1002. 'nIndexesWas' => 2,
  1003. 'msg' => 'non-_id indexes dropped for collection',
  1004. 'ok' => 1.0,
  1005. ];
  1006. $this->assertSame($expected, $this->getcollection()->deleteIndexes());
  1007. $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
  1008. }
  1009. public function testDeleteIndexesForNonExistingCollection()
  1010. {
  1011. $expected = [
  1012. 'ok' => 0.0,
  1013. 'errmsg' => 'ns not found',
  1014. 'code' => 26,
  1015. ];
  1016. $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
  1017. }
  1018. public static function dataGetIndexInfo()
  1019. {
  1020. return [
  1021. 'plainIndex' => [
  1022. 'expectedIndex' => [
  1023. 'v' => 1,
  1024. 'key' => ['foo' => 1],
  1025. 'name' => 'foo_1',
  1026. 'ns' => 'mongo-php-adapter.test',
  1027. ],
  1028. 'fields' => ['foo' => 1],
  1029. 'options' => [],
  1030. ],
  1031. 'uniqueIndex' => [
  1032. 'expectedIndex' => [
  1033. 'v' => 1,
  1034. 'key' => ['foo' => 1],
  1035. 'name' => 'foo_1',
  1036. 'ns' => 'mongo-php-adapter.test',
  1037. 'unique' => true,
  1038. ],
  1039. 'fields' => ['foo' => 1],
  1040. 'options' => ['unique' => true],
  1041. ],
  1042. 'sparseIndex' => [
  1043. 'expectedIndex' => [
  1044. 'v' => 1,
  1045. 'key' => ['foo' => 1],
  1046. 'name' => 'foo_1',
  1047. 'ns' => 'mongo-php-adapter.test',
  1048. 'sparse' => true,
  1049. ],
  1050. 'fields' => ['foo' => 1],
  1051. 'options' => ['sparse' => true],
  1052. ],
  1053. 'ttlIndex' => [
  1054. 'expectedIndex' => [
  1055. 'v' => 1,
  1056. 'key' => ['foo' => 1],
  1057. 'name' => 'foo_1',
  1058. 'ns' => 'mongo-php-adapter.test',
  1059. 'expireAfterSeconds' => 86400,
  1060. ],
  1061. 'fields' => ['foo' => 1],
  1062. 'options' => ['expireAfterSeconds' => 86400],
  1063. ],
  1064. 'textIndex' => [
  1065. 'expectedIndex' => [
  1066. 'v' => 1,
  1067. 'key' => [
  1068. '_fts' => 'text',
  1069. '_ftsx' => 1,
  1070. ],
  1071. 'name' => 'foo_text',
  1072. 'ns' => 'mongo-php-adapter.test',
  1073. 'weights' => [
  1074. 'foo' => 1,
  1075. ],
  1076. 'default_language' => 'english',
  1077. 'language_override' => 'language',
  1078. 'textIndexVersion' => 3,
  1079. ],
  1080. 'fields' => ['foo' => 'text'],
  1081. 'options' => [],
  1082. ],
  1083. 'partialFilterExpression' => [
  1084. 'expectedIndex' => [
  1085. 'v' => 1,
  1086. 'key' => ['foo' => 1],
  1087. 'name' => 'foo_1',
  1088. 'ns' => 'mongo-php-adapter.test',
  1089. 'partialFilterExpression' => [
  1090. 'bar' => ['$gt' => 1],
  1091. ],
  1092. ],
  1093. 'fields' => ['foo' => 1],
  1094. 'options' => [
  1095. 'partialFilterExpression' => ['bar' => ['$gt' => 1]],
  1096. ],
  1097. ],
  1098. 'geoSpatial' => [
  1099. 'expectedIndex' => [
  1100. 'v' => 1,
  1101. 'key' => ['foo' => '2dsphere'],
  1102. 'name' => 'foo_2dsphere',
  1103. 'ns' => 'mongo-php-adapter.test',
  1104. '2dsphereIndexVersion' => 3,
  1105. ],
  1106. 'fields' => ['foo' => '2dsphere'],
  1107. 'options' => [],
  1108. ],
  1109. 'geoHaystack' => [
  1110. 'expectedIndex' => [
  1111. 'v' => 1,
  1112. 'key' => ['foo' => 'geoHaystack', 'bar' => 1],
  1113. 'name' => 'foo_geoHaystack_bar_1',
  1114. 'ns' => 'mongo-php-adapter.test',
  1115. 'bucketSize' => 10,
  1116. ],
  1117. 'fields' => ['foo' => 'geoHaystack', 'bar' => 1],
  1118. 'options' => ['bucketSize' => 10],
  1119. ],
  1120. ];
  1121. }
  1122. /**
  1123. * @dataProvider dataGetIndexInfo
  1124. */
  1125. public function testGetIndexInfo($expectedIndex, $fields, $options)
  1126. {
  1127. $idIndex = [
  1128. 'v' => 1,
  1129. 'key' => ['_id' => 1],
  1130. 'name' => '_id_',
  1131. 'ns' => 'mongo-php-adapter.test',
  1132. ];
  1133. $expectedIndexInfo = [$idIndex, $expectedIndex];
  1134. $collection = $this->getCollection();
  1135. $collection->createIndex($fields, $options);
  1136. $this->assertEquals(
  1137. $expectedIndexInfo,
  1138. $collection->getIndexInfo()
  1139. );
  1140. }
  1141. public function testFindAndModifyUpdate()
  1142. {
  1143. $id = '54203e08d51d4a1f868b456e';
  1144. $collection = $this->getCollection();
  1145. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1146. $collection->insert($document);
  1147. $document = $collection->findAndModify(
  1148. ['_id' => new \MongoId($id)],
  1149. ['$set' => ['foo' => 'foo']]
  1150. );
  1151. $this->assertSame('bar', $document['foo']);
  1152. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1153. $this->assertSame(1, $newCollection->count());
  1154. $object = $newCollection->findOne();
  1155. $this->assertNotNull($object);
  1156. $this->assertAttributeSame('foo', 'foo', $object);
  1157. }
  1158. public function testFindAndModifyUpdateWithUpdateOptions()
  1159. {
  1160. $id = '54203e08d51d4a1f868b456e';
  1161. $collection = $this->getCollection();
  1162. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1163. $collection->insert($document);
  1164. $document = $collection->findAndModify(
  1165. ['_id' => new \MongoId($id)],
  1166. [],
  1167. [],
  1168. [
  1169. 'update' => ['bar' => 'foo']
  1170. ]
  1171. );
  1172. $this->assertSame('bar', $document['foo']);
  1173. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1174. $this->assertSame(1, $newCollection->count());
  1175. $object = $newCollection->findOne();
  1176. $this->assertNotNull($object);
  1177. $this->assertAttributeSame('foo', 'bar', $object);
  1178. $this->assertObjectNotHasAttribute('foo', $object);
  1179. }
  1180. public function testFindAndModifyWithUpdateParamAndOption()
  1181. {
  1182. $id = '54203e08d51d4a1f868b456e';
  1183. $collection = $this->getCollection();
  1184. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1185. $collection->insert($document);
  1186. $data = ['foo' => 'foo', 'bar' => 'bar'];
  1187. $this->getCollection()->findAndModify(
  1188. ['_id' => new \MongoId($id)],
  1189. [$data],
  1190. [],
  1191. [
  1192. 'update' => ['$set' => ['foo' => 'foobar']],
  1193. 'upsert' => true,
  1194. ]
  1195. );
  1196. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1197. $this->assertSame(1, $newCollection->count());
  1198. $object = $newCollection->findOne();
  1199. $this->assertNotNull($object);
  1200. $this->assertAttributeSame('foobar', 'foo', $object);
  1201. $this->assertObjectNotHasAttribute('bar', $object);
  1202. }
  1203. public function testFindAndModifyUpdateReplace()
  1204. {
  1205. $id = '54203e08d51d4a1f868b456e';
  1206. $collection = $this->getCollection();
  1207. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1208. $collection->insert($document);
  1209. $document = $collection->findAndModify(
  1210. ['_id' => new \MongoId($id)],
  1211. ['_id' => new \MongoId($id), 'foo' => 'boo']
  1212. );
  1213. $this->assertSame('bar', $document['foo']);
  1214. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1215. $this->assertSame(1, $newCollection->count());
  1216. $object = $newCollection->findOne();
  1217. $this->assertNotNull($object);
  1218. $this->assertAttributeSame('boo', 'foo', $object);
  1219. $this->assertObjectNotHasAttribute('bar', $object);
  1220. }
  1221. public function testFindAndModifyUpdateReturnNew()
  1222. {
  1223. $id = '54203e08d51d4a1f868b456e';
  1224. $collection = $this->getCollection();
  1225. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1226. $collection->insert($document);
  1227. $document = $collection->findAndModify(
  1228. ['_id' => new \MongoId($id)],
  1229. ['$set' => ['foo' => 'foo']],
  1230. null,
  1231. ['new' => true]
  1232. );
  1233. $this->assertSame('foo', $document['foo']);
  1234. }
  1235. public function testFindAndModifyWithFields()
  1236. {
  1237. $id = '54203e08d51d4a1f868b456e';
  1238. $collection = $this->getCollection();
  1239. $document = [
  1240. '_id' => new \MongoId($id),
  1241. 'foo' => 'bar',
  1242. 'bar' => 'foo',
  1243. ];
  1244. $collection->insert($document);
  1245. $document = $collection->findAndModify(
  1246. ['_id' => new \MongoId($id)],
  1247. ['$set' => ['foo' => 'foo']],
  1248. ['foo' => true]
  1249. );
  1250. $this->assertArrayNotHasKey('bar', $document);
  1251. $this->assertArrayHasKey('foo', $document);
  1252. }
  1253. public function testGroup()
  1254. {
  1255. $collection = $this->getCollection();
  1256. $document1 = ['a' => 2];
  1257. $collection->insert($document1);
  1258. $document2 = ['b' => 5];
  1259. $collection->insert($document2);
  1260. $document3 = ['a' => 1];
  1261. $collection->insert($document3);
  1262. $keys = [];
  1263. $initial = ["count" => 0];
  1264. $reduce = "function (obj, prev) { prev.count++; }";
  1265. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  1266. $result = $collection->group($keys, $initial, $reduce, $condition);
  1267. $this->assertArraySubset(
  1268. [
  1269. 'retval' => [['count' => 1.0]],
  1270. 'count' => 1.0,
  1271. 'keys' => 1,
  1272. 'ok' => 1.0,
  1273. ],
  1274. $result
  1275. );
  1276. }
  1277. public function testMapReduce()
  1278. {
  1279. $data = array(
  1280. array(
  1281. 'username' => 'jones',
  1282. 'likes' => 20.0,
  1283. 'text' => 'Hello world!'
  1284. ),
  1285. array(
  1286. 'username' => 'bob',
  1287. 'likes' => 100.0,
  1288. 'text' => 'Hello world!'
  1289. ),
  1290. array(
  1291. 'username' => 'bob',
  1292. 'likes' => 100.0,
  1293. 'text' => 'Hello world!'
  1294. ),
  1295. );
  1296. $collection = $this->getCollection();
  1297. $collection->batchInsert($data);
  1298. $map = 'function() {
  1299. emit(this.username, { count: 1, likes: this.likes });
  1300. }';
  1301. $reduce = 'function(key, values) {
  1302. var result = {count: 0, likes: 0};
  1303. values.forEach(function(value) {
  1304. result.count += value.count;
  1305. result.likes += value.likes;
  1306. });
  1307. return result;
  1308. }';
  1309. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  1310. $command = [
  1311. 'mapreduce' => $this->getCollection()->getName(),
  1312. 'map' => new \MongoCode($map),
  1313. 'reduce' => new \MongoCode($reduce),
  1314. 'query' => (object) [],
  1315. 'out' => ['inline' => true],
  1316. 'finalize' => new \MongoCode($finalize),
  1317. ];
  1318. $result = $this->getDatabase()->command($command);
  1319. $expected = [
  1320. [
  1321. '_id' => 'bob',
  1322. 'value' => [
  1323. 'count' => 2.0,
  1324. 'likes' => 200.0,
  1325. 'test' => 'test',
  1326. ],
  1327. ],
  1328. [
  1329. '_id' => 'jones',
  1330. 'value' => [
  1331. 'count' => 1.0,
  1332. 'likes' => 20.0,
  1333. 'test' => 'test',
  1334. ],
  1335. ],
  1336. ];
  1337. $this->assertSame(1.0, $result['ok']);
  1338. $this->assertSame($expected, $result['results']);
  1339. }
  1340. public function testFindAndModifyResultException()
  1341. {
  1342. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  1343. $collection = $this->getCollection();
  1344. $this->setExpectedException('MongoResultException');
  1345. $collection->findAndModify(
  1346. array("inprogress" => false, "name" => "Next promo"),
  1347. array('$unsupportedOperator' => array("tasks" => -1)),
  1348. array("tasks" => true),
  1349. array("new" => true)
  1350. );
  1351. }
  1352. public function testFindAndModifyExceptionTimeout()
  1353. {
  1354. $this->failMaxTimeMS();
  1355. $id = '54203e08d51d4a1f868b456e';
  1356. $collection = $this->getCollection();
  1357. $this->setExpectedException('MongoExecutionTimeoutException');
  1358. $document = $collection->findAndModify(
  1359. ['_id' => new \MongoId($id)],
  1360. null,
  1361. null,
  1362. ['maxTimeMS' => 1, 'remove' => true]
  1363. );
  1364. }
  1365. public function testFindAndModifyRemove()
  1366. {
  1367. $id = '54203e08d51d4a1f868b456e';
  1368. $collection = $this->getCollection();
  1369. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1370. $collection->insert($document);
  1371. $document = $collection->findAndModify(
  1372. ['_id' => new \MongoId($id)],
  1373. null,
  1374. null,
  1375. ['remove' => true]
  1376. );
  1377. $this->assertEquals('bar', $document['foo']);
  1378. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1379. $this->assertSame(0, $newCollection->count());
  1380. }
  1381. public function testValidate()
  1382. {
  1383. $collection = $this->getCollection();
  1384. $document = ['foo' => 'bar'];
  1385. $collection->insert($document);
  1386. $result = $collection->validate();
  1387. $this->assertArraySubset(
  1388. [
  1389. 'ns' => 'mongo-php-adapter.test',
  1390. 'nrecords' => 1,
  1391. 'nIndexes' => 1,
  1392. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  1393. 'valid' => true,
  1394. 'errors' => [],
  1395. ],
  1396. $result
  1397. );
  1398. }
  1399. public function testDrop()
  1400. {
  1401. $document = ['foo' => 'bar'];
  1402. $this->getCollection()->insert($document);
  1403. $expected = [
  1404. 'ns' => (string) $this->getCollection(),
  1405. 'nIndexesWas' => 1,
  1406. 'ok' => 1.0
  1407. ];
  1408. $this->assertSame($expected, $this->getCollection()->drop());
  1409. }
  1410. public function testEmptyCollectionName()
  1411. {
  1412. $this->setExpectedException('Exception', 'Collection name cannot be empty');
  1413. new \MongoCollection($this->getDatabase(), '');
  1414. }
  1415. public function testSelectCollectionWithNullBytes()
  1416. {
  1417. $this->setExpectedException('Exception', 'Collection name cannot contain null bytes');
  1418. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  1419. }
  1420. public function testSubCollectionWithNullBytes()
  1421. {
  1422. $collection = $this->getCollection();
  1423. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1424. $this->assertSame('test', $collection->getName());
  1425. }
  1426. public function testSelectCollectionWithDatabaseObject()
  1427. {
  1428. $client = $this->getClient();
  1429. $database = $this->getDatabase($client);
  1430. $collection = $client->selectCollection($database, 'test');
  1431. $this->assertSame('mongo-php-adapter.test', (string) $collection);
  1432. }
  1433. public function testHasNextLoop()
  1434. {
  1435. $collection = $this->getCollection();
  1436. for ($i = 0; $i < 5; $i++) {
  1437. $document = ['i' => $i];
  1438. $collection->insert($document);
  1439. }
  1440. $cursor = $collection->find()->sort(['i' => 1]);
  1441. $data = [];
  1442. $i = 0;
  1443. while ($cursor->hasNext()) {
  1444. $this->assertSame($i < 5, $cursor->hasNext());
  1445. $row = $cursor->getNext();
  1446. $this->assertSame($i, $row['i']);
  1447. $data[] = $row;
  1448. $i++;
  1449. }
  1450. $this->assertCount(5, $data);
  1451. }
  1452. public function testProjectionWithBSONTypes()
  1453. {
  1454. $collection = $this->getCollection();
  1455. $id = new \MongoId();
  1456. $referencedId = new \MongoId();
  1457. $data = [
  1458. '_id' => $id,
  1459. 'loveItems' => [
  1460. [
  1461. 'sellable' => [
  1462. '$ref' => 'sellables',
  1463. '$id' => $referencedId,
  1464. ]
  1465. ],
  1466. [
  1467. 'sellable' => [
  1468. '$ref' => 'sellables',
  1469. '$id' => new \MongoId(),
  1470. ]
  1471. ]
  1472. ]
  1473. ];
  1474. $collection->insert($data);
  1475. $item = $collection->findOne(
  1476. ['_id' => $id],
  1477. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1478. );
  1479. $this->assertArrayHasKey('loveItems', $item);
  1480. $this->assertCount(1, $item['loveItems']);
  1481. $cursor = $collection->find(
  1482. ['_id' => $id],
  1483. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1484. );
  1485. $items = iterator_to_array($cursor, false);
  1486. $this->assertCount(1, $items);
  1487. $this->assertCount(1, $items[0]['loveItems']);
  1488. }
  1489. public static function dataFindWithRegex()
  1490. {
  1491. return [
  1492. 'MongoRegex' => [new \MongoRegex('/^foo.*/i')],
  1493. 'BSONRegex' => [new Regex('^foo.*', 'i')],
  1494. ];
  1495. }
  1496. /**
  1497. * @dataProvider dataFindWithRegex
  1498. */
  1499. public function testFindWithRegex($regex)
  1500. {
  1501. $this->skipTestIf(extension_loaded('mongo'));
  1502. $document = ['name' => 'FOO 123'];
  1503. $this->getCollection()->insert($document);
  1504. $cursor = $this->getCollection()->find(['name' => $regex]);
  1505. $this->assertSame(1, $cursor->count());
  1506. }
  1507. }
  1508. class PrivatePropertiesStub
  1509. {
  1510. private $foo = 'bar';
  1511. }