MongoCursor.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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->cursorNeedsAdvancing) {
  199. $this->ensureIterator()->next();
  200. $this->cursorNeedsAdvancing = false;
  201. }
  202. return $this->ensureIterator()->valid();
  203. }
  204. /**
  205. * Gives the database a hint about the query
  206. * @link http://www.php.net/manual/en/mongocursor.hint.php
  207. * @param array|string $keyPattern Indexes to use for the query.
  208. * @throws MongoCursorException
  209. * @return MongoCursor Returns this cursor
  210. */
  211. public function hint($keyPattern)
  212. {
  213. $this->errorIfOpened();
  214. $this->hint = $keyPattern;
  215. return $this;
  216. }
  217. /**
  218. * Sets whether this cursor will timeout
  219. * @link http://www.php.net/manual/en/mongocursor.immortal.php
  220. * @param bool $liveForever If the cursor should be immortal.
  221. * @throws MongoCursorException
  222. * @return MongoCursor Returns this cursor
  223. */
  224. public function immortal($liveForever = true)
  225. {
  226. $this->errorIfOpened();
  227. $this->noCursorTimeout = $liveForever;
  228. return $this;
  229. }
  230. /**
  231. * Limits the number of results returned
  232. * @link http://www.php.net/manual/en/mongocursor.limit.php
  233. * @param int $num The number of results to return.
  234. * @throws MongoCursorException
  235. * @return MongoCursor Returns this cursor
  236. */
  237. public function limit($num)
  238. {
  239. $this->errorIfOpened();
  240. $this->limit = $num;
  241. return $this;
  242. }
  243. /**
  244. * @param int $ms
  245. * @return $this
  246. * @throws MongoCursorException
  247. */
  248. public function maxTimeMS($ms)
  249. {
  250. $this->errorIfOpened();
  251. $this->maxTimeMS = $ms;
  252. return $this;
  253. }
  254. /**
  255. * @link http://www.php.net/manual/en/mongocursor.partial.php
  256. * @param bool $okay [optional] <p>If receiving partial results is okay.</p>
  257. * @return MongoCursor Returns this cursor.
  258. */
  259. public function partial($okay = true)
  260. {
  261. $this->allowPartialResults = $okay;
  262. return $this;
  263. }
  264. /**
  265. * Clears the cursor
  266. * @link http://www.php.net/manual/en/mongocursor.reset.php
  267. * @return void
  268. */
  269. public function reset()
  270. {
  271. parent::reset();
  272. }
  273. /**
  274. * @link http://www.php.net/manual/en/mongocursor.setflag.php
  275. * @param int $flag
  276. * @param bool $set
  277. * @return MongoCursor
  278. */
  279. public function setFlag($flag, $set = true)
  280. {
  281. $this->notImplemented();
  282. }
  283. /**
  284. * Skips a number of results
  285. * @link http://www.php.net/manual/en/mongocursor.skip.php
  286. * @param int $num The number of results to skip.
  287. * @throws MongoCursorException
  288. * @return MongoCursor Returns this cursor
  289. */
  290. public function skip($num)
  291. {
  292. $this->errorIfOpened();
  293. $this->skip = $num;
  294. return $this;
  295. }
  296. /**
  297. * Sets whether this query can be done on a slave
  298. * This method will override the static class variable slaveOkay.
  299. * @link http://www.php.net/manual/en/mongocursor.slaveOkay.php
  300. * @param boolean $okay If it is okay to query the slave.
  301. * @throws MongoCursorException
  302. * @return MongoCursor Returns this cursor
  303. */
  304. public function slaveOkay($okay = true)
  305. {
  306. $this->errorIfOpened();
  307. $this->setReadPreferenceFromSlaveOkay($okay);
  308. return $this;
  309. }
  310. /**
  311. * Use snapshot mode for the query
  312. * @link http://www.php.net/manual/en/mongocursor.snapshot.php
  313. * @throws MongoCursorException
  314. * @return MongoCursor Returns this cursor
  315. */
  316. public function snapshot()
  317. {
  318. $this->errorIfOpened();
  319. $this->snapshot = true;
  320. return $this;
  321. }
  322. /**
  323. * Sorts the results by given fields
  324. * @link http://www.php.net/manual/en/mongocursor.sort.php
  325. * @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
  326. * @throws MongoCursorException
  327. * @return MongoCursor Returns the same cursor that this method was called on
  328. */
  329. public function sort(array $fields)
  330. {
  331. $this->errorIfOpened();
  332. $this->sort = $fields;
  333. return $this;
  334. }
  335. /**
  336. * Sets whether this cursor will be left open after fetching the last results
  337. * @link http://www.php.net/manual/en/mongocursor.tailable.php
  338. * @param bool $tail If the cursor should be tailable.
  339. * @return MongoCursor Returns this cursor
  340. */
  341. public function tailable($tail = true)
  342. {
  343. $this->errorIfOpened();
  344. $this->tailable = $tail;
  345. return $this;
  346. }
  347. /**
  348. * @return int|null
  349. */
  350. protected function convertCursorType()
  351. {
  352. if (! $this->tailable) {
  353. return null;
  354. }
  355. return $this->awaitData ? Find::TAILABLE_AWAIT : Find::TAILABLE;
  356. }
  357. protected function convertModifiers()
  358. {
  359. $modifiers = array_key_exists('modifiers', $this->options) ? $this->options['modifiers'] : [];
  360. foreach (['hint', 'snapshot'] as $modifier) {
  361. if ($this->$modifier === null) {
  362. continue;
  363. }
  364. $modifiers['$' . $modifier] = $this->$modifier;
  365. }
  366. return $modifiers;
  367. }
  368. /**
  369. * @return Cursor
  370. */
  371. protected function ensureCursor()
  372. {
  373. if ($this->cursor === null) {
  374. $this->doQuery();
  375. }
  376. return $this->cursor;
  377. }
  378. /**
  379. * @param \Traversable $traversable
  380. * @return \Generator
  381. */
  382. protected function wrapTraversable(\Traversable $traversable)
  383. {
  384. foreach ($traversable as $key => $value) {
  385. if (isset($value->_id) && ($value->_id instanceof \MongoDB\BSON\ObjectID || !is_object($value->_id))) {
  386. $key = (string) $value->_id;
  387. }
  388. yield $key => $value;
  389. }
  390. }
  391. /**
  392. * @return array
  393. */
  394. protected function getCursorInfo()
  395. {
  396. return [
  397. 'ns' => $this->ns,
  398. 'limit' => $this->limit,
  399. 'batchSize' => $this->batchSize,
  400. 'skip' => $this->skip,
  401. 'flags' => $this->flags,
  402. 'query' => $this->query,
  403. 'fields' => $this->projection,
  404. ];
  405. }
  406. /**
  407. * @return array
  408. */
  409. public function __sleep()
  410. {
  411. return [
  412. 'allowPartialResults',
  413. 'awaitData',
  414. 'flags',
  415. 'hint',
  416. 'limit',
  417. 'maxTimeMS',
  418. 'noCursorTimeout',
  419. 'optionNames',
  420. 'options',
  421. 'projection',
  422. 'query',
  423. 'skip',
  424. 'snapshot',
  425. 'sort',
  426. 'tailable',
  427. ] + parent::__sleep();
  428. }
  429. }