MongoCollectionTest.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  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. 'sequentialIntegersStartingWithOne' => [
  399. ['0' => 'foo', '1' => 'bar', '2' => 'foobar'],
  400. [1 => true, 2 => true],
  401. ['1' => 'bar', '2' => 'foobar'],
  402. ],
  403. 'nonSequentialIntegers' => [
  404. ['0' => 'foo', '1' => 'bar', '2' => 'foobar', '3' => 'barfoo'],
  405. [1 => true, 3 => true],
  406. ['1' => 'bar', '3' => 'barfoo'],
  407. ]
  408. ];
  409. }
  410. public function testFindWithProjectionAndSequentialNumericKeys()
  411. {
  412. $this->setExpectedException(\MongoException::class, 'field names must be strings', 8);
  413. $this->getCollection()->findOne([], [true, false]);
  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. }