MongoCursor.php 14 KB

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