MongoCursor.php 14 KB

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