MongoCursor.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. use Alcaeus\MongoDbAdapter\AbstractCursor;
  16. use Alcaeus\MongoDbAdapter\TypeConverter;
  17. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  18. use MongoDB\Driver\Cursor;
  19. use MongoDB\Driver\ReadPreference;
  20. use MongoDB\Operation\Find;
  21. /**
  22. * Result object for database query.
  23. * @link http://www.php.net/manual/en/class.mongocursor.php
  24. */
  25. class MongoCursor extends AbstractCursor implements Iterator
  26. {
  27. /**
  28. * @var bool
  29. */
  30. public static $slaveOkay = false;
  31. /**
  32. * @var int
  33. */
  34. public static $timeout = 30000;
  35. /**
  36. * @var array
  37. */
  38. protected $optionNames = [
  39. 'allowPartialResults',
  40. 'batchSize',
  41. 'cursorType',
  42. 'limit',
  43. 'maxTimeMS',
  44. 'modifiers',
  45. 'noCursorTimeout',
  46. 'projection',
  47. 'readPreference',
  48. 'skip',
  49. 'sort',
  50. ];
  51. /**
  52. * @var array
  53. */
  54. protected $projection;
  55. /**
  56. * @var array
  57. */
  58. protected $query;
  59. protected $allowPartialResults;
  60. protected $awaitData;
  61. protected $flags = 0;
  62. protected $hint;
  63. protected $limit;
  64. protected $maxTimeMS;
  65. protected $noCursorTimeout;
  66. protected $options = [];
  67. protected $skip;
  68. protected $snapshot;
  69. protected $sort;
  70. protected $tailable;
  71. /**
  72. * Create a new cursor
  73. * @link http://www.php.net/manual/en/mongocursor.construct.php
  74. * @param MongoClient $connection Database connection.
  75. * @param string $ns Full name of database and collection.
  76. * @param array $query Database query.
  77. * @param array $fields Fields to return.
  78. */
  79. public function __construct(MongoClient $connection, $ns, array $query = array(), array $fields = array())
  80. {
  81. parent::__construct($connection, $ns);
  82. $this->query = $query;
  83. $this->projection = $fields;
  84. }
  85. /**
  86. * Adds a top-level key/value pair to a query
  87. * @link http://www.php.net/manual/en/mongocursor.addoption.php
  88. * @param string $key Fieldname to add.
  89. * @param mixed $value Value to add.
  90. * @throws MongoCursorException
  91. * @return MongoCursor Returns this cursor
  92. */
  93. public function addOption($key, $value)
  94. {
  95. $this->errorIfOpened();
  96. $this->options[$key] = $value;
  97. return $this;
  98. }
  99. /**
  100. * (PECL mongo &gt;= 1.2.11)<br/>
  101. * Sets whether this cursor will wait for a while for a tailable cursor to return more data
  102. * @param bool $wait [optional] <p>If the cursor should wait for more data to become available.</p>
  103. * @return MongoCursor Returns this cursor.
  104. */
  105. public function awaitData($wait = true)
  106. {
  107. $this->errorIfOpened();
  108. $this->awaitData = $wait;
  109. return $this;
  110. }
  111. /**
  112. * Counts the number of results for this query
  113. * @link http://www.php.net/manual/en/mongocursor.count.php
  114. * @param bool $foundOnly Send cursor limit and skip information to the count function, if applicable.
  115. * @return int The number of documents returned by this cursor's query.
  116. */
  117. public function count($foundOnly = false)
  118. {
  119. if ($foundOnly && $this->cursor !== null) {
  120. return iterator_count($this->ensureIterator());
  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. 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. 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. $this->errorIfOpened();
  196. $this->notImplemented();
  197. }
  198. /**
  199. * Gives the database a hint about the query
  200. * @link http://www.php.net/manual/en/mongocursor.hint.php
  201. * @param array|string $keyPattern Indexes to use for the query.
  202. * @throws MongoCursorException
  203. * @return MongoCursor Returns this cursor
  204. */
  205. public function hint($keyPattern)
  206. {
  207. $this->errorIfOpened();
  208. $this->hint = $keyPattern;
  209. return $this;
  210. }
  211. /**
  212. * Sets whether this cursor will timeout
  213. * @link http://www.php.net/manual/en/mongocursor.immortal.php
  214. * @param bool $liveForever If the cursor should be immortal.
  215. * @throws MongoCursorException
  216. * @return MongoCursor Returns this cursor
  217. */
  218. public function immortal($liveForever = true)
  219. {
  220. $this->errorIfOpened();
  221. $this->noCursorTimeout = $liveForever;
  222. return $this;
  223. }
  224. /**
  225. * Limits the number of results returned
  226. * @link http://www.php.net/manual/en/mongocursor.limit.php
  227. * @param int $num The number of results to return.
  228. * @throws MongoCursorException
  229. * @return MongoCursor Returns this cursor
  230. */
  231. public function limit($num)
  232. {
  233. $this->errorIfOpened();
  234. $this->limit = $num;
  235. return $this;
  236. }
  237. /**
  238. * @param int $ms
  239. * @return $this
  240. * @throws MongoCursorException
  241. */
  242. public function maxTimeMS($ms)
  243. {
  244. $this->errorIfOpened();
  245. $this->maxTimeMS = $ms;
  246. return $this;
  247. }
  248. /**
  249. * @link http://www.php.net/manual/en/mongocursor.partial.php
  250. * @param bool $okay [optional] <p>If receiving partial results is okay.</p>
  251. * @return MongoCursor Returns this cursor.
  252. */
  253. public function partial($okay = true)
  254. {
  255. $this->allowPartialResults = $okay;
  256. return $this;
  257. }
  258. /**
  259. * Clears the cursor
  260. * @link http://www.php.net/manual/en/mongocursor.reset.php
  261. * @return void
  262. */
  263. public function reset()
  264. {
  265. parent::reset();
  266. }
  267. /**
  268. * @link http://www.php.net/manual/en/mongocursor.setflag.php
  269. * @param int $flag
  270. * @param bool $set
  271. * @return MongoCursor
  272. */
  273. public function setFlag($flag, $set = true)
  274. {
  275. $this->notImplemented();
  276. }
  277. /**
  278. * Skips a number of results
  279. * @link http://www.php.net/manual/en/mongocursor.skip.php
  280. * @param int $num The number of results to skip.
  281. * @throws MongoCursorException
  282. * @return MongoCursor Returns this cursor
  283. */
  284. public function skip($num)
  285. {
  286. $this->errorIfOpened();
  287. $this->skip = $num;
  288. return $this;
  289. }
  290. /**
  291. * Sets whether this query can be done on a slave
  292. * This method will override the static class variable slaveOkay.
  293. * @link http://www.php.net/manual/en/mongocursor.slaveOkay.php
  294. * @param boolean $okay If it is okay to query the slave.
  295. * @throws MongoCursorException
  296. * @return MongoCursor Returns this cursor
  297. */
  298. public function slaveOkay($okay = true)
  299. {
  300. $this->errorIfOpened();
  301. $this->setReadPreferenceFromSlaveOkay($okay);
  302. return $this;
  303. }
  304. /**
  305. * Use snapshot mode for the query
  306. * @link http://www.php.net/manual/en/mongocursor.snapshot.php
  307. * @throws MongoCursorException
  308. * @return MongoCursor Returns this cursor
  309. */
  310. public function snapshot()
  311. {
  312. $this->errorIfOpened();
  313. $this->snapshot = true;
  314. return $this;
  315. }
  316. /**
  317. * Sorts the results by given fields
  318. * @link http://www.php.net/manual/en/mongocursor.sort.php
  319. * @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
  320. * @throws MongoCursorException
  321. * @return MongoCursor Returns the same cursor that this method was called on
  322. */
  323. public function sort(array $fields)
  324. {
  325. $this->errorIfOpened();
  326. $this->sort = $fields;
  327. return $this;
  328. }
  329. /**
  330. * Sets whether this cursor will be left open after fetching the last results
  331. * @link http://www.php.net/manual/en/mongocursor.tailable.php
  332. * @param bool $tail If the cursor should be tailable.
  333. * @return MongoCursor Returns this cursor
  334. */
  335. public function tailable($tail = true)
  336. {
  337. $this->errorIfOpened();
  338. $this->tailable = $tail;
  339. return $this;
  340. }
  341. /**
  342. * @return int|null
  343. */
  344. protected function convertCursorType()
  345. {
  346. if (! $this->tailable) {
  347. return null;
  348. }
  349. return $this->awaitData ? Find::TAILABLE_AWAIT : Find::TAILABLE;
  350. }
  351. protected function convertModifiers()
  352. {
  353. $modifiers = array_key_exists('modifiers', $this->options) ? $this->options['modifiers'] : [];
  354. foreach (['hint', 'snapshot'] as $modifier) {
  355. if ($this->$modifier === null) {
  356. continue;
  357. }
  358. $modifiers['$' . $modifier] = $this->$modifier;
  359. }
  360. return $modifiers;
  361. }
  362. /**
  363. * @return Cursor
  364. */
  365. protected function ensureCursor()
  366. {
  367. if ($this->cursor === null) {
  368. $this->doQuery();
  369. }
  370. return $this->cursor;
  371. }
  372. /**
  373. * @return array
  374. */
  375. protected function getCursorInfo()
  376. {
  377. return [
  378. 'ns' => $this->ns,
  379. 'limit' => $this->limit,
  380. 'batchSize' => $this->batchSize,
  381. 'skip' => $this->skip,
  382. 'flags' => $this->flags,
  383. 'query' => $this->query,
  384. 'fields' => $this->projection,
  385. ];
  386. }
  387. }