MongoCursor.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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\TypeConverter;
  20. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  21. use MongoDB\Driver\Cursor;
  22. use MongoDB\Driver\ReadPreference;
  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
  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. public function count($foundOnly = false)
  121. {
  122. if ($foundOnly && $this->cursor !== null) {
  123. return iterator_count($this->ensureIterator());
  124. }
  125. $optionNames = ['hint', 'maxTimeMS'];
  126. if ($foundOnly) {
  127. $optionNames = array_merge($optionNames, ['limit', 'skip']);
  128. }
  129. $options = $this->getOptions($optionNames) + $this->options;
  130. try {
  131. $count = $this->collection->count(TypeConverter::fromLegacy($this->query), $options);
  132. } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
  133. throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
  134. } catch (\MongoDB\Driver\Exception\Exception $e) {
  135. throw ExceptionConverter::toLegacy($e);
  136. }
  137. return $count;
  138. }
  139. /**
  140. * Execute the query
  141. * @link http://www.php.net/manual/en/mongocursor.doquery.php
  142. * @throws MongoConnectionException if it cannot reach the database.
  143. * @return void
  144. */
  145. protected function doQuery()
  146. {
  147. $options = $this->getOptions() + $this->options;
  148. try {
  149. $this->cursor = $this->collection->find(TypeConverter::fromLegacy($this->query), $options);
  150. } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
  151. throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
  152. } catch (\MongoDB\Driver\Exception\Exception $e) {
  153. throw ExceptionConverter::toLegacy($e);
  154. }
  155. }
  156. /**
  157. * Return an explanation of the query, often useful for optimization and debugging
  158. * @link http://www.php.net/manual/en/mongocursor.explain.php
  159. * @return array Returns an explanation of the query.
  160. */
  161. public function explain()
  162. {
  163. $this->notImplemented();
  164. }
  165. /**
  166. * Sets the fields for a query
  167. * @link http://www.php.net/manual/en/mongocursor.fields.php
  168. * @param array $f Fields to return (or not return).
  169. * @throws MongoCursorException
  170. * @return MongoCursor
  171. */
  172. public function fields(array $f)
  173. {
  174. $this->errorIfOpened();
  175. $this->projection = $f;
  176. return $this;
  177. }
  178. /**
  179. * Advances the cursor to the next result, and returns that result
  180. * @link http://www.php.net/manual/en/mongocursor.getnext.php
  181. * @throws MongoConnectionException
  182. * @throws MongoCursorTimeoutException
  183. * @return array Returns the next object
  184. */
  185. public function getNext()
  186. {
  187. return $this->next();
  188. }
  189. /**
  190. * Checks if there are any more elements in this cursor
  191. * @link http://www.php.net/manual/en/mongocursor.hasnext.php
  192. * @throws MongoConnectionException
  193. * @throws MongoCursorTimeoutException
  194. * @return bool Returns true if there is another element
  195. */
  196. public function hasNext()
  197. {
  198. if (! $this->startedIterating) {
  199. $this->ensureIterator();
  200. $this->startedIterating = true;
  201. $this->storeIteratorState();
  202. $this->cursorNeedsAdvancing = false;
  203. } elseif ($this->cursorNeedsAdvancing) {
  204. $this->ensureIterator()->next();
  205. $this->cursorNeedsAdvancing = false;
  206. }
  207. return $this->ensureIterator()->valid();
  208. }
  209. /**
  210. * Gives the database a hint about the query
  211. * @link http://www.php.net/manual/en/mongocursor.hint.php
  212. * @param array|string $keyPattern Indexes to use for the query.
  213. * @throws MongoCursorException
  214. * @return MongoCursor Returns this cursor
  215. */
  216. public function hint($keyPattern)
  217. {
  218. $this->errorIfOpened();
  219. $this->hint = $keyPattern;
  220. return $this;
  221. }
  222. /**
  223. * Sets whether this cursor will timeout
  224. * @link http://www.php.net/manual/en/mongocursor.immortal.php
  225. * @param bool $liveForever If the cursor should be immortal.
  226. * @throws MongoCursorException
  227. * @return MongoCursor Returns this cursor
  228. */
  229. public function immortal($liveForever = true)
  230. {
  231. $this->errorIfOpened();
  232. $this->noCursorTimeout = $liveForever;
  233. return $this;
  234. }
  235. /**
  236. * Limits the number of results returned
  237. * @link http://www.php.net/manual/en/mongocursor.limit.php
  238. * @param int $num The number of results to return.
  239. * @throws MongoCursorException
  240. * @return MongoCursor Returns this cursor
  241. */
  242. public function limit($num)
  243. {
  244. $this->errorIfOpened();
  245. $this->limit = $num;
  246. return $this;
  247. }
  248. /**
  249. * @param int $ms
  250. * @return $this
  251. * @throws MongoCursorException
  252. */
  253. public function maxTimeMS($ms)
  254. {
  255. $this->errorIfOpened();
  256. $this->maxTimeMS = $ms;
  257. return $this;
  258. }
  259. /**
  260. * @link http://www.php.net/manual/en/mongocursor.partial.php
  261. * @param bool $okay [optional] <p>If receiving partial results is okay.</p>
  262. * @return MongoCursor Returns this cursor.
  263. */
  264. public function partial($okay = true)
  265. {
  266. $this->allowPartialResults = $okay;
  267. return $this;
  268. }
  269. /**
  270. * Clears the cursor
  271. * @link http://www.php.net/manual/en/mongocursor.reset.php
  272. * @return void
  273. */
  274. public function reset()
  275. {
  276. parent::reset();
  277. }
  278. /**
  279. * @link http://www.php.net/manual/en/mongocursor.setflag.php
  280. * @param int $flag
  281. * @param bool $set
  282. * @return MongoCursor
  283. */
  284. public function setFlag($flag, $set = true)
  285. {
  286. $this->notImplemented();
  287. }
  288. /**
  289. * Skips a number of results
  290. * @link http://www.php.net/manual/en/mongocursor.skip.php
  291. * @param int $num The number of results to skip.
  292. * @throws MongoCursorException
  293. * @return MongoCursor Returns this cursor
  294. */
  295. public function skip($num)
  296. {
  297. $this->errorIfOpened();
  298. $this->skip = $num;
  299. return $this;
  300. }
  301. /**
  302. * Sets whether this query can be done on a slave
  303. * This method will override the static class variable slaveOkay.
  304. * @link http://www.php.net/manual/en/mongocursor.slaveOkay.php
  305. * @param boolean $okay If it is okay to query the slave.
  306. * @throws MongoCursorException
  307. * @return MongoCursor Returns this cursor
  308. */
  309. public function slaveOkay($okay = true)
  310. {
  311. $this->errorIfOpened();
  312. $this->setReadPreferenceFromSlaveOkay($okay);
  313. return $this;
  314. }
  315. /**
  316. * Use snapshot mode for the query
  317. * @link http://www.php.net/manual/en/mongocursor.snapshot.php
  318. * @throws MongoCursorException
  319. * @return MongoCursor Returns this cursor
  320. */
  321. public function snapshot()
  322. {
  323. $this->errorIfOpened();
  324. $this->snapshot = true;
  325. return $this;
  326. }
  327. /**
  328. * Sorts the results by given fields
  329. * @link http://www.php.net/manual/en/mongocursor.sort.php
  330. * @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
  331. * @throws MongoCursorException
  332. * @return MongoCursor Returns the same cursor that this method was called on
  333. */
  334. public function sort(array $fields)
  335. {
  336. $this->errorIfOpened();
  337. $this->sort = $fields;
  338. return $this;
  339. }
  340. /**
  341. * Sets whether this cursor will be left open after fetching the last results
  342. * @link http://www.php.net/manual/en/mongocursor.tailable.php
  343. * @param bool $tail If the cursor should be tailable.
  344. * @return MongoCursor Returns this cursor
  345. */
  346. public function tailable($tail = true)
  347. {
  348. $this->errorIfOpened();
  349. $this->tailable = $tail;
  350. return $this;
  351. }
  352. /**
  353. * @return int|null
  354. */
  355. protected function convertCursorType()
  356. {
  357. if (! $this->tailable) {
  358. return null;
  359. }
  360. return $this->awaitData ? Find::TAILABLE_AWAIT : Find::TAILABLE;
  361. }
  362. protected function convertModifiers()
  363. {
  364. $modifiers = array_key_exists('modifiers', $this->options) ? $this->options['modifiers'] : [];
  365. foreach (['hint', 'snapshot'] as $modifier) {
  366. if ($this->$modifier === null) {
  367. continue;
  368. }
  369. $modifiers['$' . $modifier] = $this->$modifier;
  370. }
  371. return $modifiers;
  372. }
  373. /**
  374. * @return Cursor
  375. */
  376. protected function ensureCursor()
  377. {
  378. if ($this->cursor === null) {
  379. $this->doQuery();
  380. }
  381. return $this->cursor;
  382. }
  383. /**
  384. * @param \Traversable $traversable
  385. * @return \Generator
  386. */
  387. protected function wrapTraversable(\Traversable $traversable)
  388. {
  389. foreach ($traversable as $key => $value) {
  390. if (isset($value->_id) && ($value->_id instanceof \MongoDB\BSON\ObjectID || !is_object($value->_id))) {
  391. $key = (string) $value->_id;
  392. }
  393. yield $key => $value;
  394. }
  395. }
  396. /**
  397. * @return array
  398. */
  399. protected function getCursorInfo()
  400. {
  401. return [
  402. 'ns' => $this->ns,
  403. 'limit' => $this->limit,
  404. 'batchSize' => $this->batchSize,
  405. 'skip' => $this->skip,
  406. 'flags' => $this->flags,
  407. 'query' => $this->query,
  408. 'fields' => $this->projection,
  409. ];
  410. }
  411. /**
  412. * @return array
  413. */
  414. public function __sleep()
  415. {
  416. return [
  417. 'allowPartialResults',
  418. 'awaitData',
  419. 'flags',
  420. 'hint',
  421. 'limit',
  422. 'maxTimeMS',
  423. 'noCursorTimeout',
  424. 'optionNames',
  425. 'options',
  426. 'projection',
  427. 'query',
  428. 'skip',
  429. 'snapshot',
  430. 'sort',
  431. 'tailable',
  432. ] + parent::__sleep();
  433. }
  434. }