MongoCollectionTest.php 49 KB

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