MongoCollection.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. /**
  18. * Represents a database collection.
  19. * @link http://www.php.net/manual/en/class.mongocollection.php
  20. */
  21. class MongoCollection
  22. {
  23. use Helper\ReadPreference;
  24. use Helper\SlaveOkay;
  25. use Helper\WriteConcern;
  26. const ASCENDING = 1;
  27. const DESCENDING = -1;
  28. /**
  29. * @var MongoDB
  30. */
  31. public $db = NULL;
  32. /**
  33. * @var string
  34. */
  35. protected $name;
  36. /**
  37. * @var \MongoDB\Collection
  38. */
  39. protected $collection;
  40. /**
  41. * Creates a new collection
  42. *
  43. * @link http://www.php.net/manual/en/mongocollection.construct.php
  44. * @param MongoDB $db Parent database.
  45. * @param string $name Name for this collection.
  46. * @throws Exception
  47. * @return MongoCollection
  48. */
  49. public function __construct(MongoDB $db, $name)
  50. {
  51. $this->db = $db;
  52. $this->name = $name;
  53. $this->setReadPreferenceFromArray($db->getReadPreference());
  54. $this->setWriteConcernFromArray($db->getWriteConcern());
  55. $this->createCollectionObject();
  56. }
  57. /**
  58. * Gets the underlying collection for this object
  59. *
  60. * @internal This part is not of the ext-mongo API and should not be used
  61. * @return \MongoDB\Collection
  62. */
  63. public function getCollection()
  64. {
  65. return $this->collection;
  66. }
  67. /**
  68. * String representation of this collection
  69. *
  70. * @link http://www.php.net/manual/en/mongocollection.--tostring.php
  71. * @return string Returns the full name of this collection.
  72. */
  73. public function __toString()
  74. {
  75. return (string) $this->db . '.' . $this->name;
  76. }
  77. /**
  78. * Gets a collection
  79. *
  80. * @link http://www.php.net/manual/en/mongocollection.get.php
  81. * @param string $name The next string in the collection name.
  82. * @return MongoCollection
  83. */
  84. public function __get($name)
  85. {
  86. // Handle w and wtimeout properties that replicate data stored in $readPreference
  87. if ($name === 'w' || $name === 'wtimeout') {
  88. return $this->getWriteConcern()[$name];
  89. }
  90. return $this->db->selectCollection($this->name . '.' . $name);
  91. }
  92. /**
  93. * @param string $name
  94. * @param mixed $value
  95. */
  96. public function __set($name, $value)
  97. {
  98. if ($name === 'w' || $name === 'wtimeout') {
  99. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  100. $this->createCollectionObject();
  101. }
  102. }
  103. /**
  104. * Perform an aggregation using the aggregation framework
  105. *
  106. * @link http://www.php.net/manual/en/mongocollection.aggregate.php
  107. * @param array $pipeline
  108. * @param array $op
  109. * @return array
  110. */
  111. public function aggregate(array $pipeline, array $op = [])
  112. {
  113. if (! TypeConverter::isNumericArray($pipeline)) {
  114. $pipeline = [];
  115. $options = [];
  116. $i = 0;
  117. foreach (func_get_args() as $operator) {
  118. $i++;
  119. if (! is_array($operator)) {
  120. trigger_error("Argument $i is not an array", E_WARNING);
  121. return;
  122. }
  123. $pipeline[] = $operator;
  124. }
  125. } else {
  126. $options = $op;
  127. }
  128. $command = [
  129. 'aggregate' => $this->name,
  130. 'pipeline' => $pipeline
  131. ];
  132. $command += $options;
  133. return $this->db->command($command);
  134. }
  135. /**
  136. * Execute an aggregation pipeline command and retrieve results through a cursor
  137. *
  138. * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
  139. * @param array $pipeline
  140. * @param array $options
  141. * @return MongoCommandCursor
  142. */
  143. public function aggregateCursor(array $pipeline, array $options = [])
  144. {
  145. // Build command manually, can't use mongo-php-library here
  146. $command = [
  147. 'aggregate' => $this->name,
  148. 'pipeline' => $pipeline
  149. ];
  150. // Convert cursor option
  151. if (! isset($options['cursor']) || $options['cursor'] === true || $options['cursor'] === []) {
  152. // Cursor option needs to be an object convert bools and empty arrays since those won't be handled by TypeConverter
  153. $options['cursor'] = new \stdClass;
  154. }
  155. $command += $options;
  156. $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
  157. $cursor->setReadPreference($this->getReadPreference());
  158. return $cursor;
  159. }
  160. /**
  161. * Returns this collection's name
  162. *
  163. * @link http://www.php.net/manual/en/mongocollection.getname.php
  164. * @return string
  165. */
  166. public function getName()
  167. {
  168. return $this->name;
  169. }
  170. /**
  171. * {@inheritdoc}
  172. */
  173. public function setReadPreference($readPreference, $tags = null)
  174. {
  175. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  176. $this->createCollectionObject();
  177. return $result;
  178. }
  179. /**
  180. * {@inheritdoc}
  181. */
  182. public function setWriteConcern($wstring, $wtimeout = 0)
  183. {
  184. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  185. $this->createCollectionObject();
  186. return $result;
  187. }
  188. /**
  189. * Drops this collection
  190. *
  191. * @link http://www.php.net/manual/en/mongocollection.drop.php
  192. * @return array Returns the database response.
  193. */
  194. public function drop()
  195. {
  196. return TypeConverter::convertObjectToLegacyArray($this->collection->drop());
  197. }
  198. /**
  199. * Validates this collection
  200. *
  201. * @link http://www.php.net/manual/en/mongocollection.validate.php
  202. * @param bool $scan_data Only validate indices, not the base collection.
  203. * @return array Returns the database's evaluation of this object.
  204. */
  205. public function validate($scan_data = FALSE)
  206. {
  207. $command = [
  208. 'validate' => $this->name,
  209. 'full' => $scan_data,
  210. ];
  211. return $this->db->command($command);
  212. }
  213. /**
  214. * Inserts an array into the collection
  215. *
  216. * @link http://www.php.net/manual/en/mongocollection.insert.php
  217. * @param array|object $a
  218. * @param array $options
  219. * @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.
  220. * @throws MongoCursorException if the "w" option is set and the write fails.
  221. * @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.
  222. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
  223. */
  224. public function insert($a, array $options = [])
  225. {
  226. $result = $this->collection->insertOne(
  227. TypeConverter::convertLegacyArrayToObject($a),
  228. $this->convertWriteConcernOptions($options)
  229. );
  230. if (! $result->isAcknowledged()) {
  231. return true;
  232. }
  233. return [
  234. 'ok' => 1.0,
  235. 'n' => 0,
  236. 'err' => null,
  237. 'errmsg' => null,
  238. ];
  239. }
  240. /**
  241. * Inserts multiple documents into this collection
  242. *
  243. * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
  244. * @param array $a An array of arrays.
  245. * @param array $options Options for the inserts.
  246. * @throws MongoCursorException
  247. * @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.
  248. */
  249. public function batchInsert(array $a, array $options = [])
  250. {
  251. $result = $this->collection->insertMany(
  252. TypeConverter::convertLegacyArrayToObject($a),
  253. $this->convertWriteConcernOptions($options)
  254. );
  255. if (! $result->isAcknowledged()) {
  256. return true;
  257. }
  258. return [
  259. 'connectionId' => 0,
  260. 'n' => 0,
  261. 'syncMillis' => 0,
  262. 'writtenTo' => null,
  263. 'err' => null,
  264. 'errmsg' => null,
  265. ];
  266. }
  267. /**
  268. * Update records based on a given criteria
  269. *
  270. * @link http://www.php.net/manual/en/mongocollection.update.php
  271. * @param array $criteria Description of the objects to update.
  272. * @param array $newobj The object with which to update the matching records.
  273. * @param array $options
  274. * @throws MongoCursorException
  275. * @return boolean
  276. */
  277. public function update(array $criteria , array $newobj, array $options = [])
  278. {
  279. $multiple = isset($options['multiple']) ? $options['multiple'] : false;
  280. $method = $multiple ? 'updateMany' : 'updateOne';
  281. unset($options['multiple']);
  282. /** @var \MongoDB\UpdateResult $result */
  283. $result = $this->collection->$method(
  284. TypeConverter::convertLegacyArrayToObject($criteria),
  285. TypeConverter::convertLegacyArrayToObject($newobj),
  286. $this->convertWriteConcernOptions($options)
  287. );
  288. if (! $result->isAcknowledged()) {
  289. return true;
  290. }
  291. return [
  292. 'ok' => 1.0,
  293. 'nModified' => $result->getModifiedCount(),
  294. 'n' => $result->getMatchedCount(),
  295. 'err' => null,
  296. 'errmsg' => null,
  297. 'updatedExisting' => $result->getUpsertedCount() == 0,
  298. ];
  299. }
  300. /**
  301. * Remove records from this collection
  302. *
  303. * @link http://www.php.net/manual/en/mongocollection.remove.php
  304. * @param array $criteria Query criteria for the documents to delete.
  305. * @param array $options An array of options for the remove operation.
  306. * @throws MongoCursorException
  307. * @throws MongoCursorTimeoutException
  308. * @return bool|array Returns an array containing the status of the removal
  309. * if the "w" option is set. Otherwise, returns TRUE.
  310. */
  311. public function remove(array $criteria = [], array $options = [])
  312. {
  313. $multiple = isset($options['justOne']) ? !$options['justOne'] : false;
  314. $method = $multiple ? 'deleteMany' : 'deleteOne';
  315. return $this->collection->$method($criteria, $options);
  316. }
  317. /**
  318. * Querys this collection
  319. *
  320. * @link http://www.php.net/manual/en/mongocollection.find.php
  321. * @param array $query The fields for which to search.
  322. * @param array $fields Fields of the results to return.
  323. * @return MongoCursor
  324. */
  325. public function find(array $query = [], array $fields = [])
  326. {
  327. $cursor = new MongoCursor($this->db->getConnection(), (string)$this, $query, $fields);
  328. $cursor->setReadPreference($this->getReadPreference());
  329. return $cursor;
  330. }
  331. /**
  332. * Retrieve a list of distinct values for the given key across a collection
  333. *
  334. * @link http://www.php.net/manual/ru/mongocollection.distinct.php
  335. * @param string $key The key to use.
  336. * @param array $query An optional query parameters
  337. * @return array|bool Returns an array of distinct values, or FALSE on failure
  338. */
  339. public function distinct($key, array $query = [])
  340. {
  341. return array_map([TypeConverter::class, 'convertToLegacyType'], $this->collection->distinct($key, $query));
  342. }
  343. /**
  344. * Update a document and return it
  345. * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
  346. * @param array $query The query criteria to search for.
  347. * @param array $update The update criteria.
  348. * @param array $fields Optionally only return these fields.
  349. * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
  350. * @return array Returns the original document, or the modified document when new is set.
  351. */
  352. public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
  353. {
  354. $query = TypeConverter::convertLegacyArrayToObject($query);
  355. if (isset($options['remove'])) {
  356. unset($options['remove']);
  357. $document = $this->collection->findOneAndDelete($query, $options);
  358. } else {
  359. $update = is_array($update) ? TypeConverter::convertLegacyArrayToObject($update) : [];
  360. if (isset($options['new'])) {
  361. $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
  362. unset($options['new']);
  363. }
  364. $options['projection'] = is_array($fields) ? TypeConverter::convertLegacyArrayToObject($fields) : [];
  365. $document = $this->collection->findOneAndUpdate($query, $update, $options);
  366. }
  367. if ($document) {
  368. $document = TypeConverter::convertObjectToLegacyArray($document);
  369. }
  370. return $document;
  371. }
  372. /**
  373. * Querys this collection, returning a single element
  374. * @link http://www.php.net/manual/en/mongocollection.findone.php
  375. * @param array $query The fields for which to search.
  376. * @param array $fields Fields of the results to return.
  377. * @return array|null
  378. */
  379. public function findOne(array $query = [], array $fields = [])
  380. {
  381. $document = $this->collection->findOne(TypeConverter::convertLegacyArrayToObject($query), ['projection' => $fields]);
  382. if ($document !== null) {
  383. $document = TypeConverter::convertObjectToLegacyArray($document);
  384. }
  385. return $document;
  386. }
  387. /**
  388. * Creates an index on the given field(s), or does nothing if the index already exists
  389. * @link http://www.php.net/manual/en/mongocollection.createindex.php
  390. * @param array $keys Field or fields to use as index.
  391. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  392. * @return array Returns the database response.
  393. *
  394. * @todo This method does not yet return the correct result
  395. */
  396. public function createIndex(array $keys, array $options = [])
  397. {
  398. // Note: this is what the result array should look like
  399. // $expected = [
  400. // 'createdCollectionAutomatically' => true,
  401. // 'numIndexesBefore' => 1,
  402. // 'numIndexesAfter' => 2,
  403. // 'ok' => 1.0
  404. // ];
  405. return $this->collection->createIndex($keys, $options);
  406. }
  407. /**
  408. * @deprecated Use MongoCollection::createIndex() instead.
  409. * Creates an index on the given field(s), or does nothing if the index already exists
  410. * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
  411. * @param array $keys Field or fields to use as index.
  412. * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
  413. * @return boolean always true
  414. */
  415. public function ensureIndex(array $keys, array $options = [])
  416. {
  417. $this->createIndex($keys, $options);
  418. return true;
  419. }
  420. /**
  421. * Deletes an index from this collection
  422. * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
  423. * @param string|array $keys Field or fields from which to delete the index.
  424. * @return array Returns the database response.
  425. */
  426. public function deleteIndex($keys)
  427. {
  428. if (is_string($keys)) {
  429. $indexName = $keys;
  430. } elseif (is_array($keys)) {
  431. $indexName = self::toIndexString($keys);
  432. } else {
  433. throw new \InvalidArgumentException();
  434. }
  435. return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndex($indexName));
  436. }
  437. /**
  438. * Delete all indexes for this collection
  439. * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
  440. * @return array Returns the database response.
  441. */
  442. public function deleteIndexes()
  443. {
  444. return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndexes());
  445. }
  446. /**
  447. * Returns an array of index names for this collection
  448. * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
  449. * @return array Returns a list of index names.
  450. */
  451. public function getIndexInfo()
  452. {
  453. $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
  454. return [
  455. 'v' => $indexInfo->getVersion(),
  456. 'key' => $indexInfo->getKey(),
  457. 'name' => $indexInfo->getName(),
  458. 'ns' => $indexInfo->getNamespace(),
  459. ];
  460. };
  461. return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
  462. }
  463. /**
  464. * Counts the number of documents in this collection
  465. * @link http://www.php.net/manual/en/mongocollection.count.php
  466. * @param array|stdClass $query
  467. * @return int Returns the number of documents matching the query.
  468. */
  469. public function count($query = [])
  470. {
  471. return $this->collection->count($query);
  472. }
  473. /**
  474. * Saves an object to this collection
  475. *
  476. * @link http://www.php.net/manual/en/mongocollection.save.php
  477. * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
  478. * @param array $options Options for the save.
  479. * @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.
  480. * @throws MongoCursorException if the "w" option is set and the write fails.
  481. * @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.
  482. * @return array|boolean If w was set, returns an array containing the status of the save.
  483. * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  484. */
  485. public function save($a, array $options = [])
  486. {
  487. if (is_object($a)) {
  488. $a = (array)$a;
  489. }
  490. if ( ! array_key_exists('_id', $a)) {
  491. $id = new \MongoId();
  492. } else {
  493. $id = $a['_id'];
  494. unset($a['_id']);
  495. }
  496. $filter = ['_id' => $id];
  497. $filter = TypeConverter::convertLegacyArrayToObject($filter);
  498. $a = TypeConverter::convertLegacyArrayToObject($a);
  499. return $this->collection->updateOne($filter, ['$set' => $a], ['upsert' => true]);
  500. }
  501. /**
  502. * Creates a database reference
  503. *
  504. * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  505. * @param array $a Object to which to create a reference.
  506. * @return array Returns a database reference array.
  507. */
  508. public function createDBRef(array $a)
  509. {
  510. return \MongoDBRef::create($this->name, $a['_id']);
  511. }
  512. /**
  513. * Fetches the document pointed to by a database reference
  514. *
  515. * @link http://www.php.net/manual/en/mongocollection.getdbref.php
  516. * @param array $ref A database reference.
  517. * @return array Returns the database document pointed to by the reference.
  518. */
  519. public function getDBRef(array $ref)
  520. {
  521. return \MongoDBRef::get($this->db, $ref);
  522. }
  523. /**
  524. * @param mixed $keys
  525. * @static
  526. * @return string
  527. */
  528. protected static function toIndexString($keys)
  529. {
  530. $result = '';
  531. foreach ($keys as $name => $direction) {
  532. $result .= sprintf('%s_%d', $name, $direction);
  533. }
  534. return $result;
  535. }
  536. /**
  537. * Performs an operation similar to SQL's GROUP BY command
  538. *
  539. * @link http://www.php.net/manual/en/mongocollection.group.php
  540. * @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.
  541. * @param array $initial Initial value of the aggregation counter object.
  542. * @param MongoCode $reduce A function that aggregates (reduces) the objects iterated.
  543. * @param array $condition An condition that must be true for a row to be considered.
  544. * @return array
  545. */
  546. public function group($keys, array $initial, $reduce, array $condition = [])
  547. {
  548. if (is_string($reduce)) {
  549. $reduce = new MongoCode($reduce);
  550. }
  551. if ( ! $reduce instanceof MongoCode) {
  552. throw new \InvalidArgumentExcption('reduce parameter should be a string or MongoCode instance.');
  553. }
  554. $command = [
  555. 'group' => [
  556. 'ns' => $this->name,
  557. '$reduce' => (string)$reduce,
  558. 'initial' => $initial,
  559. 'cond' => $condition,
  560. ],
  561. ];
  562. if ($keys instanceof MongoCode) {
  563. $command['group']['$keyf'] = (string)$keys;
  564. } else {
  565. $command['group']['key'] = $keys;
  566. }
  567. if (array_key_exists('condition', $condition)) {
  568. $command['group']['cond'] = $condition['condition'];
  569. }
  570. if (array_key_exists('finalize', $condition)) {
  571. if ($condition['finalize'] instanceof MongoCode) {
  572. $condition['finalize'] = (string)$condition['finalize'];
  573. }
  574. $command['group']['finalize'] = $condition['finalize'];
  575. }
  576. return $this->db->command($command);
  577. }
  578. /**
  579. * Returns an array of cursors to iterator over a full collection in parallel
  580. *
  581. * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
  582. * @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.
  583. * @return MongoCommandCursor[]
  584. */
  585. public function parallelCollectionScan($num_cursors)
  586. {
  587. $this->notImplemented();
  588. }
  589. protected function notImplemented()
  590. {
  591. throw new \Exception('Not implemented');
  592. }
  593. /**
  594. * @return \MongoDB\Collection
  595. */
  596. private function createCollectionObject()
  597. {
  598. $options = [
  599. 'readPreference' => $this->readPreference,
  600. 'writeConcern' => $this->writeConcern,
  601. ];
  602. if ($this->collection === null) {
  603. $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
  604. } else {
  605. $this->collection = $this->collection->withOptions($options);
  606. }
  607. }
  608. /**
  609. * @param array $options
  610. * @return array
  611. */
  612. private function convertWriteConcernOptions(array $options)
  613. {
  614. if (isset($options['safe'])) {
  615. $options['w'] = ($options['safe']) ? 1 : 0;
  616. }
  617. if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
  618. $options['wTimeoutMS'] = $options['wtimeout'];
  619. }
  620. if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
  621. $collectionWriteConcern = $this->getWriteConcern();
  622. $writeConcern = $this->createWriteConcernFromParameters(
  623. isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
  624. isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
  625. );
  626. $options['writeConcern'] = $writeConcern;
  627. }
  628. unset($options['safe']);
  629. unset($options['w']);
  630. unset($options['wTimeout']);
  631. unset($options['wTimeoutMS']);
  632. return $options;
  633. }
  634. }