MongoCollectionTest.php 60 KB

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