MongoCollection.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. */
  15. use Alcaeus\MongoDbAdapter\Helper;
  16. use Alcaeus\MongoDbAdapter\TypeConverter;
  17. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  18. /**
  19. * Represents a database collection.
  20. * @link http://www.php.net/manual/en/class.mongocollection.php
  21. */
  22. class MongoCollection
  23. {
  24. use Helper\ReadPreference;
  25. use Helper\SlaveOkay;
  26. use Helper\WriteConcern;
  27. const ASCENDING = 1;
  28. const DESCENDING = -1;
  29. /**
  30. * @var MongoDB
  31. */
  32. public $db = NULL;
  33. /**
  34. * @var string
  35. */
  36. protected $name;
  37. /**
  38. * @var \MongoDB\Collection
  39. */
  40. protected $collection;
  41. /**
  42. * Creates a new collection
  43. *
  44. * @link http://www.php.net/manual/en/mongocollection.construct.php
  45. * @param MongoDB $db Parent database.
  46. * @param string $name Name for this collection.
  47. * @throws Exception
  48. */
  49. public function __construct(MongoDB $db, $name)
  50. {
  51. $this->checkCollectionName($name);
  52. $this->db = $db;
  53. $this->name = $name;
  54. $this->setReadPreferenceFromArray($db->getReadPreference());
  55. $this->setWriteConcernFromArray($db->getWriteConcern());
  56. $this->createCollectionObject();
  57. }
  58. /**
  59. * Gets the underlying collection for this object
  60. *
  61. * @internal This part is not of the ext-mongo API and should not be used
  62. * @return \MongoDB\Collection
  63. */
  64. public function getCollection()
  65. {
  66. return $this->collection;
  67. }
  68. /**
  69. * String representation of this collection
  70. *
  71. * @link http://www.php.net/manual/en/mongocollection.--tostring.php
  72. * @return string Returns the full name of this collection.
  73. */
  74. public function __toString()
  75. {
  76. return (string) $this->db . '.' . $this->name;
  77. }
  78. /**
  79. * Gets a collection
  80. *
  81. * @link http://www.php.net/manual/en/mongocollection.get.php
  82. * @param string $name The next string in the collection name.
  83. * @return MongoCollection
  84. */
  85. public function __get($name)
  86. {
  87. // Handle w and wtimeout properties that replicate data stored in $readPreference
  88. if ($name === 'w' || $name === 'wtimeout') {
  89. return $this->getWriteConcern()[$name];
  90. }
  91. return $this->db->selectCollection($this->name . '.' . str_replace(chr(0), '', $name));
  92. }
  93. /**
  94. * @param string $name
  95. * @param mixed $value
  96. */
  97. public function __set($name, $value)
  98. {
  99. if ($name === 'w' || $name === 'wtimeout') {
  100. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  101. $this->createCollectionObject();
  102. }
  103. }
  104. /**
  105. * Perform an aggregation using the aggregation framework
  106. *
  107. * @link http://www.php.net/manual/en/mongocollection.aggregate.php
  108. * @param array $pipeline
  109. * @param array $op
  110. * @return array
  111. */
  112. public function aggregate(array $pipeline, array $op = [])
  113. {
  114. if (! TypeConverter::isNumericArray($pipeline)) {
  115. $pipeline = [];
  116. $options = [];
  117. $i = 0;
  118. foreach (func_get_args() as $operator) {
  119. $i++;
  120. if (! is_array($operator)) {
  121. trigger_error("Argument $i is not an array", E_WARNING);
  122. return;
  123. }
  124. $pipeline[] = $operator;
  125. }
  126. } else {
  127. $options = $op;
  128. }
  129. if (isset($options['cursor'])) {
  130. $options['useCursor'] = true;
  131. if (isset($options['cursor']['batchSize'])) {
  132. $options['batchSize'] = $options['cursor']['batchSize'];
  133. }
  134. unset($options['cursor']);
  135. } else {
  136. $options['useCursor'] = false;
  137. }
  138. try {
  139. return $this->collection->aggregate(TypeConverter::fromLegacy($pipeline), $options);
  140. } catch (\MongoDB\Driver\Exception\Exception $e) {
  141. throw ExceptionConverter::toLegacy($e);
  142. }
  143. }
  144. /**
  145. * Execute an aggregation pipeline command and retrieve results through a cursor
  146. *
  147. * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
  148. * @param array $pipeline
  149. * @param array $options
  150. * @return MongoCommandCursor
  151. */
  152. public function aggregateCursor(array $pipeline, array $options = [])
  153. {
  154. // Build command manually, can't use mongo-php-library here
  155. $command = [
  156. 'aggregate' => $this->name,
  157. 'pipeline' => $pipeline
  158. ];
  159. // Convert cursor option
  160. if (! isset($options['cursor'])) {
  161. $options['cursor'] = new \stdClass();
  162. }
  163. $command += $options;
  164. $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
  165. $cursor->setReadPreference($this->getReadPreference());
  166. return $cursor;
  167. }
  168. /**
  169. * Returns this collection's name
  170. *
  171. * @link http://www.php.net/manual/en/mongocollection.getname.php
  172. * @return string
  173. */
  174. public function getName()
  175. {
  176. return $this->name;
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function setReadPreference($readPreference, $tags = null)
  182. {
  183. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  184. $this->createCollectionObject();
  185. return $result;
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function setWriteConcern($wstring, $wtimeout = 0)
  191. {
  192. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  193. $this->createCollectionObject();
  194. return $result;
  195. }
  196. /**
  197. * Drops this collection
  198. *
  199. * @link http://www.php.net/manual/en/mongocollection.drop.php
  200. * @return array Returns the database response.
  201. */
  202. public function drop()
  203. {
  204. return TypeConverter::toLegacy($this->collection->drop());
  205. }
  206. /**
  207. * Validates this collection
  208. *
  209. * @link http://www.php.net/manual/en/mongocollection.validate.php
  210. * @param bool $scan_data Only validate indices, not the base collection.
  211. * @return array Returns the database's evaluation of this object.
  212. */
  213. public function validate($scan_data = FALSE)
  214. {
  215. $command = [
  216. 'validate' => $this->name,
  217. 'full' => $scan_data,
  218. ];
  219. return $this->db->command($command);
  220. }
  221. /**
  222. * Inserts an array into the collection
  223. *
  224. * @link http://www.php.net/manual/en/mongocollection.insert.php
  225. * @param array|object $a
  226. * @param array $options
  227. * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
  228. * @throws MongoCursorException if the "w" option is set and the write fails.
  229. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
  230. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
  231. */
  232. public function insert(&$a, array $options = [])
  233. {
  234. if (! $this->ensureDocumentHasMongoId($a)) {
  235. trigger_error(sprintf('%s(): expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  236. return;
  237. }
  238. if (! count((array)$a)) {
  239. throw new \MongoException('document must be an array or object');
  240. }
  241. try {
  242. $result = $this->collection->insertOne(
  243. TypeConverter::fromLegacy($a),
  244. $this->convertWriteConcernOptions($options)
  245. );
  246. } catch (\MongoDB\Driver\Exception\Exception $e) {
  247. throw ExceptionConverter::toLegacy($e);
  248. }
  249. if (! $result->isAcknowledged()) {
  250. return true;
  251. }
  252. return [
  253. 'ok' => 1.0,
  254. 'n' => 0,
  255. 'err' => null,
  256. 'errmsg' => null,
  257. ];
  258. }
  259. /**
  260. * Inserts multiple documents into this collection
  261. *
  262. * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
  263. * @param array $a An array of arrays.
  264. * @param array $options Options for the inserts.
  265. * @throws MongoCursorException
  266. * @return mixed If "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occured ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.
  267. */
  268. public function batchInsert(array &$a, array $options = [])
  269. {
  270. if (empty($a)) {
  271. throw new \MongoException('No write ops were included in the batch');
  272. }
  273. $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
  274. foreach ($a as $key => $item) {
  275. try {
  276. if (! $this->ensureDocumentHasMongoId($a[$key])) {
  277. if ($continueOnError) {
  278. unset($a[$key]);
  279. } else {
  280. trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
  281. return;
  282. }
  283. }
  284. } catch (MongoException $e) {
  285. if ( ! $continueOnError) {
  286. throw $e;
  287. }
  288. }
  289. }
  290. try {
  291. $result = $this->collection->insertMany(
  292. TypeConverter::fromLegacy(array_values($a)),
  293. $this->convertWriteConcernOptions($options)
  294. );
  295. } catch (\MongoDB\Driver\Exception\Exception $e) {
  296. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  297. }
  298. if (! $result->isAcknowledged()) {
  299. return true;
  300. }
  301. return [
  302. 'ok' => 1.0,
  303. 'connectionId' => 0,
  304. 'n' => 0,
  305. 'syncMillis' => 0,
  306. 'writtenTo' => null,
  307. 'err' => null,
  308. ];
  309. }
  310. /**
  311. * Update records based on a given criteria
  312. *
  313. * @link http://www.php.net/manual/en/mongocollection.update.php
  314. * @param array $criteria Description of the objects to update.
  315. * @param array $newobj The object with which to update the matching records.
  316. * @param array $options
  317. * @throws MongoCursorException
  318. * @return boolean
  319. */
  320. public function update(array $criteria , array $newobj, array $options = [])
  321. {
  322. $multiple = isset($options['multiple']) ? $options['multiple'] : false;
  323. $isReplace = ! \MongoDB\is_first_key_operator($newobj);
  324. if ($isReplace && $multiple) {
  325. throw new \MongoWriteConcernException('multi update only works with $ operators', 9);
  326. }
  327. unset($options['multiple']);
  328. $method = $isReplace ? 'replace' : 'update';
  329. $method .= $multiple ? 'Many' : 'One';
  330. try {
  331. /** @var \MongoDB\UpdateResult $result */
  332. $result = $this->collection->$method(
  333. TypeConverter::fromLegacy($criteria),
  334. TypeConverter::fromLegacy($newobj),
  335. $this->convertWriteConcernOptions($options)
  336. );
  337. } catch (\MongoDB\Driver\Exception\Exception $e) {
  338. throw ExceptionConverter::toLegacy($e);
  339. }
  340. if (! $result->isAcknowledged()) {
  341. return true;
  342. }
  343. return [
  344. 'ok' => 1.0,
  345. 'nModified' => $result->getModifiedCount(),
  346. 'n' => $result->getMatchedCount(),
  347. 'err' => null,
  348. 'errmsg' => null,
  349. 'updatedExisting' => $result->getUpsertedCount() == 0,
  350. ];
  351. }
  352. /**
  353. * Remove records from this collection
  354. *
  355. * @link http://www.php.net/manual/en/mongocollection.remove.php
  356. * @param array $criteria Query criteria for the documents to delete.
  357. * @param array $options An array of options for the remove operation.
  358. * @throws MongoCursorException
  359. * @throws MongoCursorTimeoutException
  360. * @return bool|array Returns an array containing the status of the removal
  361. * if the "w" option is set. Otherwise, returns TRUE.
  362. */
  363. public function remove(array $criteria = [], array $options = [])
  364. {
  365. $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
  366. $method = $multiple ? 'deleteMany' : 'deleteOne';
  367. try {
  368. /** @var \MongoDB\DeleteResult $result */
  369. $result = $this->collection->$method(
  370. TypeConverter::fromLegacy($criteria),
  371. $this->convertWriteConcernOptions($options)
  372. );
  373. } catch (\MongoDB\Driver\Exception\Exception $e) {
  374. throw ExceptionConverter::toLegacy($e);
  375. }
  376. if (! $result->isAcknowledged()) {
  377. return true;
  378. }
  379. return [
  380. 'ok' => 1.0,
  381. 'n' => $result->getDeletedCount(),
  382. 'err' => null,
  383. 'errmsg' => null
  384. ];
  385. }
  386. /**
  387. * Querys this collection
  388. *
  389. * @link http://www.php.net/manual/en/mongocollection.find.php
  390. * @param array $query The fields for which to search.
  391. * @param array $fields Fields of the results to return.
  392. * @return MongoCursor
  393. */
  394. public function find(array $query = [], array $fields = [])
  395. {
  396. $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
  397. $cursor->setReadPreference($this->getReadPreference());
  398. return $cursor;
  399. }
  400. /**
  401. * Retrieve a list of distinct values for the given key across a collection
  402. *
  403. * @link http://www.php.net/manual/ru/mongocollection.distinct.php
  404. * @param string $key The key to use.
  405. * @param array $query An optional query parameters
  406. * @return array|bool Returns an array of distinct values, or FALSE on failure
  407. */
  408. public function distinct($key, array $query = [])
  409. {
  410. try {
  411. return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, $query));
  412. } catch (\MongoDB\Driver\Exception\Exception $e) {
  413. return false;
  414. }
  415. }
  416. /**
  417. * Update a document and return it
  418. *
  419. * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
  420. * @param array $query The query criteria to search for.
  421. * @param array $update The update criteria.
  422. * @param array $fields Optionally only return these fields.
  423. * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
  424. * @return array Returns the original document, or the modified document when new is set.
  425. */
  426. public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
  427. {
  428. $query = TypeConverter::fromLegacy($query);
  429. try {
  430. if (isset($options['remove'])) {
  431. unset($options['remove']);
  432. $document = $this->collection->findOneAndDelete($query, $options);
  433. } else {
  434. $update = is_array($update) ? TypeConverter::fromLegacy($update) : [];
  435. if (isset($options['new'])) {
  436. $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
  437. unset($options['new']);
  438. }
  439. $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
  440. if (! \MongoDB\is_first_key_operator($update)) {
  441. $document = $this->collection->findOneAndReplace($query, $update, $options);
  442. } else {
  443. $document = $this->collection->findOneAndUpdate($query, $update, $options);
  444. }
  445. }
  446. } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
  447. throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
  448. } catch (\MongoDB\Driver\Exception\Exception $e) {
  449. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  450. }
  451. if ($document) {
  452. $document = TypeConverter::toLegacy($document);
  453. }
  454. return $document;
  455. }
  456. /**
  457. * Querys this collection, returning a single element
  458. *
  459. * @link http://www.php.net/manual/en/mongocollection.findone.php
  460. * @param array $query The fields for which to search.
  461. * @param array $fields Fields of the results to return.
  462. * @param array $options
  463. * @return array|null
  464. */
  465. public function findOne(array $query = [], array $fields = [], array $options = [])
  466. {
  467. $options = ['projection' => $fields] + $options;
  468. try {
  469. $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
  470. } catch (\MongoDB\Driver\Exception\Exception $e) {
  471. throw ExceptionConverter::toLegacy($e);
  472. }
  473. if ($document !== null) {
  474. $document = TypeConverter::toLegacy($document);
  475. }
  476. return $document;
  477. }
  478. /**
  479. * Creates an index on the given field(s), or does nothing if the index already exists
  480. *
  481. * @link http://www.php.net/manual/en/mongocollection.createindex.php
  482. * @param array $keys Field or fields to use as index.
  483. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  484. * @return array Returns the database response.
  485. */
  486. public function createIndex($keys, array $options = [])
  487. {
  488. if (is_string($keys)) {
  489. if (empty($keys)) {
  490. throw new MongoException('empty string passed as key field');
  491. }
  492. $keys = [$keys => 1];
  493. }
  494. if (is_object($keys)) {
  495. $keys = (array) $keys;
  496. }
  497. if (! is_array($keys) || ! count($keys)) {
  498. throw new MongoException('index specification has no elements');
  499. }
  500. if (! isset($options['name'])) {
  501. $options['name'] = \MongoDB\generate_index_name($keys);
  502. }
  503. $indexes = iterator_to_array($this->collection->listIndexes());
  504. $indexCount = count($indexes);
  505. $collectionExists = true;
  506. $indexExists = false;
  507. // listIndexes returns 0 for non-existing collections while the legacy driver returns 1
  508. if ($indexCount === 0) {
  509. $collectionExists = false;
  510. $indexCount = 1;
  511. }
  512. foreach ($indexes as $index) {
  513. if ($index->getKey() === $keys || $index->getName() === $options['name']) {
  514. $indexExists = true;
  515. break;
  516. }
  517. }
  518. try {
  519. $this->collection->createIndex($keys, $this->convertWriteConcernOptions($options));
  520. } catch (\MongoDB\Driver\Exception\Exception $e) {
  521. throw ExceptionConverter::toLegacy($e, 'MongoResultException');
  522. }
  523. $result = [
  524. 'createdCollectionAutomatically' => !$collectionExists,
  525. 'numIndexesBefore' => $indexCount,
  526. 'numIndexesAfter' => $indexCount,
  527. 'note' => 'all indexes already exist',
  528. 'ok' => 1.0,
  529. ];
  530. if (! $indexExists) {
  531. $result['numIndexesAfter']++;
  532. unset($result['note']);
  533. }
  534. return $result;
  535. }
  536. /**
  537. * Creates an index on the given field(s), or does nothing if the index already exists
  538. *
  539. * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
  540. * @param array $keys Field or fields to use as index.
  541. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  542. * @return array Returns the database response.
  543. * @deprecated Use MongoCollection::createIndex() instead.
  544. */
  545. public function ensureIndex(array $keys, array $options = [])
  546. {
  547. return $this->createIndex($keys, $options);
  548. }
  549. /**
  550. * Deletes an index from this collection
  551. *
  552. * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
  553. * @param string|array $keys Field or fields from which to delete the index.
  554. * @return array Returns the database response.
  555. */
  556. public function deleteIndex($keys)
  557. {
  558. if (is_string($keys)) {
  559. $indexName = $keys;
  560. if (! preg_match('#_-?1$#', $indexName)) {
  561. $indexName .= '_1';
  562. }
  563. } elseif (is_array($keys)) {
  564. $indexName = \MongoDB\generate_index_name($keys);
  565. } else {
  566. throw new \InvalidArgumentException();
  567. }
  568. try {
  569. return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
  570. } catch (\MongoDB\Driver\Exception\Exception $e) {
  571. return ExceptionConverter::toResultArray($e) + ['nIndexesWas' => count($this->getIndexInfo())];
  572. }
  573. }
  574. /**
  575. * Delete all indexes for this collection
  576. *
  577. * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
  578. * @return array Returns the database response.
  579. */
  580. public function deleteIndexes()
  581. {
  582. try {
  583. return TypeConverter::toLegacy($this->collection->dropIndexes());
  584. } catch (\MongoDB\Driver\Exception\Exception $e) {
  585. return ExceptionConverter::toResultArray($e);
  586. }
  587. }
  588. /**
  589. * Returns an array of index names for this collection
  590. *
  591. * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
  592. * @return array Returns a list of index names.
  593. */
  594. public function getIndexInfo()
  595. {
  596. $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
  597. return [
  598. 'v' => $indexInfo->getVersion(),
  599. 'key' => $indexInfo->getKey(),
  600. 'name' => $indexInfo->getName(),
  601. 'ns' => $indexInfo->getNamespace(),
  602. ];
  603. };
  604. return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
  605. }
  606. /**
  607. * Counts the number of documents in this collection
  608. *
  609. * @link http://www.php.net/manual/en/mongocollection.count.php
  610. * @param array|stdClass $query
  611. * @param array $options
  612. * @return int Returns the number of documents matching the query.
  613. */
  614. public function count($query = [], array $options = [])
  615. {
  616. try {
  617. return $this->collection->count(TypeConverter::fromLegacy($query), $options);
  618. } catch (\MongoDB\Driver\Exception\Exception $e) {
  619. throw ExceptionConverter::toLegacy($e);
  620. }
  621. }
  622. /**
  623. * Saves an object to this collection
  624. *
  625. * @link http://www.php.net/manual/en/mongocollection.save.php
  626. * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
  627. * @param array $options Options for the save.
  628. * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
  629. * @throws MongoCursorException if the "w" option is set and the write fails.
  630. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
  631. * @return array|boolean If w was set, returns an array containing the status of the save.
  632. * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  633. */
  634. public function save(&$a, array $options = [])
  635. {
  636. $id = $this->ensureDocumentHasMongoId($a);
  637. $document = (array) $a;
  638. $options['upsert'] = true;
  639. try {
  640. /** @var \MongoDB\UpdateResult $result */
  641. $result = $this->collection->replaceOne(
  642. TypeConverter::fromLegacy(['_id' => $id]),
  643. TypeConverter::fromLegacy($document),
  644. $this->convertWriteConcernOptions($options)
  645. );
  646. if (! $result->isAcknowledged()) {
  647. return true;
  648. }
  649. $resultArray = [
  650. 'ok' => 1.0,
  651. 'nModified' => $result->getModifiedCount(),
  652. 'n' => $result->getUpsertedCount() + $result->getModifiedCount(),
  653. 'err' => null,
  654. 'errmsg' => null,
  655. 'updatedExisting' => $result->getUpsertedCount() == 0,
  656. ];
  657. if ($result->getUpsertedId() !== null) {
  658. $resultArray['upserted'] = TypeConverter::toLegacy($result->getUpsertedId());
  659. }
  660. return $resultArray;
  661. } catch (\MongoDB\Driver\Exception\Exception $e) {
  662. throw ExceptionConverter::toLegacy($e);
  663. }
  664. }
  665. /**
  666. * Creates a database reference
  667. *
  668. * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  669. * @param array|object $document_or_id Object to which to create a reference.
  670. * @return array Returns a database reference array.
  671. */
  672. public function createDBRef($document_or_id)
  673. {
  674. if ($document_or_id instanceof \MongoId) {
  675. $id = $document_or_id;
  676. } elseif (is_object($document_or_id)) {
  677. if (! isset($document_or_id->_id)) {
  678. return null;
  679. }
  680. $id = $document_or_id->_id;
  681. } elseif (is_array($document_or_id)) {
  682. if (! isset($document_or_id['_id'])) {
  683. return null;
  684. }
  685. $id = $document_or_id['_id'];
  686. } else {
  687. $id = $document_or_id;
  688. }
  689. return MongoDBRef::create($this->name, $id);
  690. }
  691. /**
  692. * Fetches the document pointed to by a database reference
  693. *
  694. * @link http://www.php.net/manual/en/mongocollection.getdbref.php
  695. * @param array $ref A database reference.
  696. * @return array Returns the database document pointed to by the reference.
  697. */
  698. public function getDBRef(array $ref)
  699. {
  700. return $this->db->getDBRef($ref);
  701. }
  702. /**
  703. * Performs an operation similar to SQL's GROUP BY command
  704. *
  705. * @link http://www.php.net/manual/en/mongocollection.group.php
  706. * @param mixed $keys Fields to group by. If an array or non-code object is passed, it will be the key used to group results.
  707. * @param array $initial Initial value of the aggregation counter object.
  708. * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
  709. * @param array $condition An condition that must be true for a row to be considered.
  710. * @return array
  711. */
  712. public function group($keys, array $initial, $reduce, array $condition = [])
  713. {
  714. if (is_string($reduce)) {
  715. $reduce = new MongoCode($reduce);
  716. }
  717. $command = [
  718. 'group' => [
  719. 'ns' => $this->name,
  720. '$reduce' => (string)$reduce,
  721. 'initial' => $initial,
  722. 'cond' => $condition,
  723. ],
  724. ];
  725. if ($keys instanceof MongoCode) {
  726. $command['group']['$keyf'] = (string)$keys;
  727. } else {
  728. $command['group']['key'] = $keys;
  729. }
  730. if (array_key_exists('condition', $condition)) {
  731. $command['group']['cond'] = $condition['condition'];
  732. }
  733. if (array_key_exists('finalize', $condition)) {
  734. if ($condition['finalize'] instanceof MongoCode) {
  735. $condition['finalize'] = (string)$condition['finalize'];
  736. }
  737. $command['group']['finalize'] = $condition['finalize'];
  738. }
  739. return $this->db->command($command);
  740. }
  741. /**
  742. * Returns an array of cursors to iterator over a full collection in parallel
  743. *
  744. * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
  745. * @param int $num_cursors The number of cursors to request from the server. Please note, that the server can return less cursors than you requested.
  746. * @return MongoCommandCursor[]
  747. */
  748. public function parallelCollectionScan($num_cursors)
  749. {
  750. $this->notImplemented();
  751. }
  752. protected function notImplemented()
  753. {
  754. throw new \Exception('Not implemented');
  755. }
  756. /**
  757. * @return \MongoDB\Collection
  758. */
  759. private function createCollectionObject()
  760. {
  761. $options = [
  762. 'readPreference' => $this->readPreference,
  763. 'writeConcern' => $this->writeConcern,
  764. ];
  765. if ($this->collection === null) {
  766. $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
  767. } else {
  768. $this->collection = $this->collection->withOptions($options);
  769. }
  770. }
  771. /**
  772. * Converts legacy write concern options to a WriteConcern object
  773. *
  774. * @param array $options
  775. * @return array
  776. */
  777. private function convertWriteConcernOptions(array $options)
  778. {
  779. if (isset($options['safe'])) {
  780. $options['w'] = ($options['safe']) ? 1 : 0;
  781. }
  782. if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
  783. $options['wTimeoutMS'] = $options['wtimeout'];
  784. }
  785. if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
  786. $collectionWriteConcern = $this->getWriteConcern();
  787. $writeConcern = $this->createWriteConcernFromParameters(
  788. isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
  789. isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
  790. );
  791. $options['writeConcern'] = $writeConcern;
  792. }
  793. unset($options['safe']);
  794. unset($options['w']);
  795. unset($options['wTimeout']);
  796. unset($options['wTimeoutMS']);
  797. return $options;
  798. }
  799. /**
  800. * @param array|object $document
  801. * @return MongoId
  802. */
  803. private function ensureDocumentHasMongoId(&$document)
  804. {
  805. $checkKeys = function($array) {
  806. foreach (array_keys($array) as $key) {
  807. if (empty($key) && $key !== 0) {
  808. throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
  809. }
  810. }
  811. };
  812. if (is_array($document)) {
  813. if (! isset($document['_id'])) {
  814. $document['_id'] = new \MongoId();
  815. }
  816. $checkKeys($document);
  817. return $document['_id'];
  818. } elseif (is_object($document)) {
  819. $reflectionObject = new \ReflectionObject($document);
  820. foreach ($reflectionObject->getProperties() as $property) {
  821. if (! $property->isPublic()) {
  822. throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
  823. }
  824. }
  825. if (! isset($document->_id)) {
  826. $document->_id = new \MongoId();
  827. }
  828. $checkKeys((array) $document);
  829. return $document->_id;
  830. }
  831. return null;
  832. }
  833. private function checkCollectionName($name)
  834. {
  835. if (empty($name)) {
  836. throw new Exception('Collection name cannot be empty');
  837. } elseif (strpos($name, chr(0)) !== false) {
  838. throw new Exception('Collection name cannot contain null bytes');
  839. }
  840. }
  841. /**
  842. * @return array
  843. */
  844. public function __sleep()
  845. {
  846. return ['db', 'name'];
  847. }
  848. }