MongoCursor.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. if (class_exists('MongoCursor', false)) {
  16. return;
  17. }
  18. use Alcaeus\MongoDbAdapter\AbstractCursor;
  19. use Alcaeus\MongoDbAdapter\CursorIterator;
  20. use Alcaeus\MongoDbAdapter\TypeConverter;
  21. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  22. use MongoDB\Driver\Cursor;
  23. use MongoDB\Operation\Find;
  24. /**
  25. * Result object for database query.
  26. * @link http://www.php.net/manual/en/class.mongocursor.php
  27. */
  28. class MongoCursor extends AbstractCursor implements Iterator, Countable, MongoCursorInterface
  29. {
  30. /**
  31. * @var bool
  32. */
  33. public static $slaveOkay = false;
  34. /**
  35. * @var int
  36. */
  37. public static $timeout = 30000;
  38. /**
  39. * @var array
  40. */
  41. protected $optionNames = [
  42. 'allowPartialResults',
  43. 'batchSize',
  44. 'cursorType',
  45. 'limit',
  46. 'maxTimeMS',
  47. 'modifiers',
  48. 'noCursorTimeout',
  49. 'projection',
  50. 'readPreference',
  51. 'skip',
  52. 'sort',
  53. ];
  54. /**
  55. * @var array
  56. */
  57. protected $projection;
  58. /**
  59. * @var array
  60. */
  61. protected $query;
  62. protected $allowPartialResults;
  63. protected $awaitData;
  64. protected $flags = 0;
  65. protected $hint;
  66. protected $limit;
  67. protected $maxTimeMS;
  68. protected $noCursorTimeout;
  69. protected $options = [];
  70. protected $skip;
  71. protected $snapshot;
  72. protected $sort;
  73. protected $tailable;
  74. /**
  75. * Create a new cursor
  76. * @link http://www.php.net/manual/en/mongocursor.construct.php
  77. * @param MongoClient $connection Database connection.
  78. * @param string $ns Full name of database and collection.
  79. * @param array $query Database query.
  80. * @param array $fields Fields to return.
  81. */
  82. public function __construct(MongoClient $connection, $ns, array $query = array(), array $fields = array())
  83. {
  84. parent::__construct($connection, $ns);
  85. $this->query = $query;
  86. $this->projection = $fields;
  87. }
  88. /**
  89. * Adds a top-level key/value pair to a query
  90. * @link http://www.php.net/manual/en/mongocursor.addoption.php
  91. * @param string $key Fieldname to add.
  92. * @param mixed $value Value to add.
  93. * @throws MongoCursorException
  94. * @return MongoCursor Returns this cursor
  95. */
  96. public function addOption($key, $value)
  97. {
  98. $this->errorIfOpened();
  99. $this->options[$key] = $value;
  100. return $this;
  101. }
  102. /**
  103. * (PECL mongo &gt;= 1.2.11)<br/>
  104. * Sets whether this cursor will wait for a while for a tailable cursor to return more data
  105. * @param bool $wait [optional] <p>If the cursor should wait for more data to become available.</p>
  106. * @return MongoCursor Returns this cursor.
  107. */
  108. public function awaitData($wait = true)
  109. {
  110. $this->errorIfOpened();
  111. $this->awaitData = $wait;
  112. return $this;
  113. }
  114. /**
  115. * Counts the number of results for this query
  116. * @link http://www.php.net/manual/en/mongocursor.count.php
  117. * @param bool $foundOnly Send cursor limit and skip information to the count function, if applicable.
  118. * @return int The number of documents returned by this cursor's query.
  119. */
  120. #[\ReturnTypeWillChange]
  121. public function count($foundOnly = false)
  122. {
  123. $optionNames = ['hint', 'maxTimeMS'];
  124. if ($foundOnly) {
  125. $optionNames = array_merge($optionNames, ['limit', 'skip']);
  126. }
  127. $options = $this->getOptions($optionNames) + $this->options;
  128. try {
  129. $count = $this->collection->count(TypeConverter::fromLegacy($this->query), $options);
  130. } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
  131. throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
  132. } catch (\MongoDB\Driver\Exception\Exception $e) {
  133. throw ExceptionConverter::toLegacy($e);
  134. }
  135. return $count;
  136. }
  137. /**
  138. * Execute the query
  139. * @link http://www.php.net/manual/en/mongocursor.doquery.php
  140. * @throws MongoConnectionException if it cannot reach the database.
  141. * @return void
  142. */
  143. protected function doQuery()
  144. {
  145. $options = $this->getOptions() + $this->options;
  146. try {
  147. $this->cursor = $this->collection->find(TypeConverter::fromLegacy($this->query), $options);
  148. } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
  149. throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
  150. } catch (\MongoDB\Driver\Exception\Exception $e) {
  151. throw ExceptionConverter::toLegacy($e);
  152. }
  153. }
  154. /**
  155. * Return an explanation of the query, often useful for optimization and debugging
  156. * @link http://www.php.net/manual/en/mongocursor.explain.php
  157. * @return array Returns an explanation of the query.
  158. */
  159. public function explain()
  160. {
  161. $optionNames = [
  162. 'allowPartialResults',
  163. 'batchSize',
  164. 'cursorType',
  165. 'limit',
  166. 'maxTimeMS',
  167. 'noCursorTimeout',
  168. 'projection',
  169. 'skip',
  170. 'sort',
  171. ];
  172. $options = $this->getOptions($optionNames);
  173. $command = [
  174. 'explain' => [
  175. 'find' => $this->collection->getCollectionName(),
  176. 'filter' => TypeConverter::fromLegacy($this->query),
  177. ] + $options,
  178. ];
  179. $explained = TypeConverter::toLegacy(iterator_to_array($this->db->command($command))[0]);
  180. unset($explained['ok']);
  181. return $explained;
  182. }
  183. /**
  184. * Sets the fields for a query
  185. * @link http://www.php.net/manual/en/mongocursor.fields.php
  186. * @param array $f Fields to return (or not return).
  187. * @throws MongoCursorException
  188. * @return MongoCursor
  189. */
  190. public function fields(array $f)
  191. {
  192. $this->errorIfOpened();
  193. $this->projection = $f;
  194. return $this;
  195. }
  196. /**
  197. * Advances the cursor to the next result, and returns that result
  198. * @link http://www.php.net/manual/en/mongocursor.getnext.php
  199. * @throws MongoConnectionException
  200. * @throws MongoCursorTimeoutException
  201. * @return array Returns the next object
  202. */
  203. public function getNext()
  204. {
  205. return $this->next();
  206. }
  207. /**
  208. * Checks if there are any more elements in this cursor
  209. * @link http://www.php.net/manual/en/mongocursor.hasnext.php
  210. * @throws MongoConnectionException
  211. * @throws MongoCursorTimeoutException
  212. * @return bool Returns true if there is another element
  213. */
  214. public function hasNext()
  215. {
  216. if (! $this->startedIterating) {
  217. $this->ensureIterator();
  218. $this->startedIterating = true;
  219. $this->storeIteratorState();
  220. $this->cursorNeedsAdvancing = false;
  221. } elseif ($this->cursorNeedsAdvancing) {
  222. $this->ensureIterator()->next();
  223. $this->cursorNeedsAdvancing = false;
  224. }
  225. return $this->ensureIterator()->valid();
  226. }
  227. /**
  228. * Gives the database a hint about the query
  229. * @link http://www.php.net/manual/en/mongocursor.hint.php
  230. * @param array|string $keyPattern Indexes to use for the query.
  231. * @throws MongoCursorException
  232. * @return MongoCursor Returns this cursor
  233. */
  234. public function hint($keyPattern)
  235. {
  236. $this->errorIfOpened();
  237. $this->hint = $keyPattern;
  238. return $this;
  239. }
  240. /**
  241. * Sets whether this cursor will timeout
  242. * @link http://www.php.net/manual/en/mongocursor.immortal.php
  243. * @param bool $liveForever If the cursor should be immortal.
  244. * @throws MongoCursorException
  245. * @return MongoCursor Returns this cursor
  246. */
  247. public function immortal($liveForever = true)
  248. {
  249. $this->errorIfOpened();
  250. $this->noCursorTimeout = $liveForever;
  251. return $this;
  252. }
  253. /**
  254. * Limits the number of results returned
  255. * @link http://www.php.net/manual/en/mongocursor.limit.php
  256. * @param int $num The number of results to return.
  257. * @throws MongoCursorException
  258. * @return MongoCursor Returns this cursor
  259. */
  260. public function limit($num)
  261. {
  262. $this->errorIfOpened();
  263. $this->limit = $num;
  264. return $this;
  265. }
  266. /**
  267. * @param int $ms
  268. * @return $this
  269. * @throws MongoCursorException
  270. */
  271. public function maxTimeMS($ms)
  272. {
  273. $this->errorIfOpened();
  274. $this->maxTimeMS = $ms;
  275. return $this;
  276. }
  277. /**
  278. * @link http://www.php.net/manual/en/mongocursor.partial.php
  279. * @param bool $okay [optional] <p>If receiving partial results is okay.</p>
  280. * @return MongoCursor Returns this cursor.
  281. */
  282. public function partial($okay = true)
  283. {
  284. $this->allowPartialResults = $okay;
  285. return $this;
  286. }
  287. /**
  288. * Clears the cursor
  289. * @link http://www.php.net/manual/en/mongocursor.reset.php
  290. * @return void
  291. */
  292. public function reset()
  293. {
  294. parent::reset();
  295. }
  296. /**
  297. * @link http://www.php.net/manual/en/mongocursor.setflag.php
  298. * @param int $flag
  299. * @param bool $set
  300. * @return MongoCursor
  301. */
  302. public function setFlag($flag, $set = true)
  303. {
  304. $this->notImplemented();
  305. }
  306. /**
  307. * Skips a number of results
  308. * @link http://www.php.net/manual/en/mongocursor.skip.php
  309. * @param int $num The number of results to skip.
  310. * @throws MongoCursorException
  311. * @return MongoCursor Returns this cursor
  312. */
  313. public function skip($num)
  314. {
  315. $this->errorIfOpened();
  316. $this->skip = $num;
  317. return $this;
  318. }
  319. /**
  320. * Sets whether this query can be done on a slave
  321. * This method will override the static class variable slaveOkay.
  322. * @link http://www.php.net/manual/en/mongocursor.slaveOkay.php
  323. * @param boolean $okay If it is okay to query the slave.
  324. * @throws MongoCursorException
  325. * @return MongoCursor Returns this cursor
  326. */
  327. public function slaveOkay($okay = true)
  328. {
  329. $this->errorIfOpened();
  330. $this->setReadPreferenceFromSlaveOkay($okay);
  331. return $this;
  332. }
  333. /**
  334. * Use snapshot mode for the query
  335. * @link http://www.php.net/manual/en/mongocursor.snapshot.php
  336. * @throws MongoCursorException
  337. * @return MongoCursor Returns this cursor
  338. */
  339. public function snapshot()
  340. {
  341. $this->errorIfOpened();
  342. $this->snapshot = true;
  343. return $this;
  344. }
  345. /**
  346. * Sorts the results by given fields
  347. * @link http://www.php.net/manual/en/mongocursor.sort.php
  348. * @param array $fields An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort
  349. * @throws MongoCursorException
  350. * @return MongoCursor Returns the same cursor that this method was called on
  351. */
  352. public function sort(array $fields)
  353. {
  354. $this->errorIfOpened();
  355. $this->sort = $fields;
  356. return $this;
  357. }
  358. /**
  359. * Sets whether this cursor will be left open after fetching the last results
  360. * @link http://www.php.net/manual/en/mongocursor.tailable.php
  361. * @param bool $tail If the cursor should be tailable.
  362. * @return MongoCursor Returns this cursor
  363. */
  364. public function tailable($tail = true)
  365. {
  366. $this->errorIfOpened();
  367. $this->tailable = $tail;
  368. return $this;
  369. }
  370. /**
  371. * @return int|null
  372. */
  373. protected function convertCursorType()
  374. {
  375. if (! $this->tailable) {
  376. return null;
  377. }
  378. return $this->awaitData ? Find::TAILABLE_AWAIT : Find::TAILABLE;
  379. }
  380. /**
  381. * @return array
  382. */
  383. protected function convertModifiers()
  384. {
  385. $modifiers = array_key_exists('modifiers', $this->options) ? $this->options['modifiers'] : [];
  386. foreach (['hint', 'snapshot'] as $modifier) {
  387. if ($this->$modifier === null) {
  388. continue;
  389. }
  390. $modifiers['$' . $modifier] = $this->$modifier;
  391. }
  392. return $modifiers;
  393. }
  394. /**
  395. * @return array
  396. */
  397. protected function convertProjection()
  398. {
  399. return TypeConverter::convertProjection($this->projection);
  400. }
  401. /**
  402. * @return Cursor
  403. */
  404. protected function ensureCursor()
  405. {
  406. if ($this->cursor === null) {
  407. $this->doQuery();
  408. }
  409. return $this->cursor;
  410. }
  411. /**
  412. * @param \Traversable $traversable
  413. * @return CursorIterator
  414. */
  415. protected function wrapTraversable(\Traversable $traversable)
  416. {
  417. return new CursorIterator($traversable, true);
  418. }
  419. /**
  420. * @return array
  421. */
  422. protected function getCursorInfo()
  423. {
  424. return [
  425. 'ns' => $this->ns,
  426. 'limit' => $this->limit,
  427. 'batchSize' => (int) $this->batchSize,
  428. 'skip' => $this->skip,
  429. 'flags' => $this->flags,
  430. 'query' => $this->query,
  431. 'fields' => $this->projection,
  432. ];
  433. }
  434. /**
  435. * @return array
  436. */
  437. public function __sleep()
  438. {
  439. return [
  440. 'allowPartialResults',
  441. 'awaitData',
  442. 'flags',
  443. 'hint',
  444. 'limit',
  445. 'maxTimeMS',
  446. 'noCursorTimeout',
  447. 'optionNames',
  448. 'options',
  449. 'projection',
  450. 'query',
  451. 'skip',
  452. 'snapshot',
  453. 'sort',
  454. 'tailable',
  455. ] + parent::__sleep();
  456. }
  457. }