MongoCursor.php 12 KB

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