AbstractCursor.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. namespace Alcaeus\MongoDbAdapter;
  16. use Alcaeus\MongoDbAdapter\Helper\ReadPreference;
  17. use MongoDB\Collection;
  18. use MongoDB\Driver\Cursor;
  19. use ReturnTypeWillChange;
  20. /**
  21. * @internal
  22. */
  23. abstract class AbstractCursor
  24. {
  25. use ReadPreference;
  26. /**
  27. * @var int|null
  28. */
  29. protected $batchSize = null;
  30. /**
  31. * @var Collection
  32. */
  33. protected $collection;
  34. /**
  35. * @var \MongoClient
  36. */
  37. protected $connection;
  38. /**
  39. * @var Cursor
  40. */
  41. protected $cursor;
  42. /**
  43. * @var \MongoDB\Database
  44. */
  45. protected $db;
  46. /**
  47. * @var CursorIterator
  48. */
  49. protected $iterator;
  50. /**
  51. * @var string
  52. */
  53. protected $ns;
  54. /**
  55. * @var bool
  56. */
  57. protected $startedIterating = false;
  58. /**
  59. * @var bool
  60. */
  61. protected $cursorNeedsAdvancing = true;
  62. /**
  63. * @var mixed
  64. */
  65. private $current = null;
  66. /**
  67. * @var mixed
  68. */
  69. private $key = null;
  70. /**
  71. * @var mixed
  72. */
  73. private $valid = false;
  74. /**
  75. * @var int
  76. */
  77. protected $position = 0;
  78. /**
  79. * @var array
  80. */
  81. protected $optionNames = [
  82. 'batchSize',
  83. 'readPreference',
  84. ];
  85. /**
  86. * @return Cursor
  87. */
  88. abstract protected function ensureCursor();
  89. /**
  90. * @return array
  91. */
  92. abstract protected function getCursorInfo();
  93. /**
  94. * Create a new cursor
  95. * @link http://www.php.net/manual/en/mongocursor.construct.php
  96. * @param \MongoClient $connection Database connection.
  97. * @param string $ns Full name of database and collection.
  98. */
  99. public function __construct(\MongoClient $connection, $ns)
  100. {
  101. $this->connection = $connection;
  102. $this->ns = $ns;
  103. $nsParts = explode('.', $ns);
  104. $dbName = array_shift($nsParts);
  105. $collectionName = implode('.', $nsParts);
  106. $this->db = $connection->selectDB($dbName)->getDb();
  107. if ($collectionName) {
  108. $this->collection = $connection->selectCollection($dbName, $collectionName)->getCollection();
  109. }
  110. }
  111. /**
  112. * Returns the current element
  113. * @link http://www.php.net/manual/en/mongocursor.current.php
  114. * @return array
  115. */
  116. #[ReturnTypeWillChange]
  117. public function current()
  118. {
  119. return $this->current;
  120. }
  121. /**
  122. * Returns the current result's _id
  123. * @link http://www.php.net/manual/en/mongocursor.key.php
  124. * @return string The current result's _id as a string.
  125. */
  126. #[ReturnTypeWillChange]
  127. public function key()
  128. {
  129. return $this->key;
  130. }
  131. /**
  132. * Advances the cursor to the next result, and returns that result
  133. * @link http://www.php.net/manual/en/mongocursor.next.php
  134. * @throws \MongoConnectionException
  135. * @throws \MongoCursorTimeoutException
  136. * @return array Returns the next object
  137. */
  138. #[ReturnTypeWillChange]
  139. public function next()
  140. {
  141. if (! $this->startedIterating) {
  142. $this->ensureIterator();
  143. $this->startedIterating = true;
  144. } else {
  145. if ($this->cursorNeedsAdvancing) {
  146. $this->ensureIterator()->next();
  147. }
  148. $this->cursorNeedsAdvancing = true;
  149. $this->position++;
  150. }
  151. return $this->storeIteratorState();
  152. }
  153. /**
  154. * Returns the cursor to the beginning of the result set
  155. * @throws \MongoConnectionException
  156. * @throws \MongoCursorTimeoutException
  157. * @return void
  158. */
  159. #[ReturnTypeWillChange]
  160. public function rewind()
  161. {
  162. // We can recreate the cursor to allow it to be rewound
  163. $this->reset();
  164. $this->startedIterating = true;
  165. $this->position = 0;
  166. $this->ensureIterator()->rewind();
  167. $this->storeIteratorState();
  168. }
  169. /**
  170. * Checks if the cursor is reading a valid result.
  171. * @link http://www.php.net/manual/en/mongocursor.valid.php
  172. * @return boolean If the current result is not null.
  173. */
  174. #[ReturnTypeWillChange]
  175. public function valid()
  176. {
  177. return $this->valid;
  178. }
  179. /**
  180. * Limits the number of elements returned in one batch.
  181. *
  182. * @link http://docs.php.net/manual/en/mongocursor.batchsize.php
  183. * @param int|null $batchSize The number of results to return per batch
  184. * @return $this Returns this cursor.
  185. */
  186. public function batchSize($batchSize)
  187. {
  188. $this->batchSize = $batchSize;
  189. return $this;
  190. }
  191. /**
  192. * Checks if there are documents that have not been sent yet from the database for this cursor
  193. * @link http://www.php.net/manual/en/mongocursor.dead.php
  194. * @return boolean Returns if there are more results that have not been sent to the client, yet.
  195. */
  196. public function dead()
  197. {
  198. return $this->ensureCursor()->isDead();
  199. }
  200. /**
  201. * @return array
  202. */
  203. public function info()
  204. {
  205. return $this->getCursorInfo() + $this->getIterationInfo();
  206. }
  207. /**
  208. * @link http://www.php.net/manual/en/mongocursor.setreadpreference.php
  209. * @param string $readPreference
  210. * @param array $tags
  211. * @return $this Returns this cursor.
  212. */
  213. public function setReadPreference($readPreference, $tags = null)
  214. {
  215. $this->setReadPreferenceFromParameters($readPreference, $tags);
  216. return $this;
  217. }
  218. /**
  219. * Sets a client-side timeout for this query
  220. * @link http://www.php.net/manual/en/mongocursor.timeout.php
  221. * @param int $ms The number of milliseconds for the cursor to wait for a response. By default, the cursor will wait forever.
  222. * @return $this Returns this cursor
  223. */
  224. public function timeout($ms)
  225. {
  226. trigger_error('The ' . __METHOD__ . ' method is not implemented in mongo-php-adapter', E_USER_WARNING);
  227. return $this;
  228. }
  229. /**
  230. * Applies all options set on the cursor, overwriting any options that have already been set
  231. *
  232. * @param array $optionNames Array of option names to be applied (will be read from properties)
  233. * @return array
  234. */
  235. protected function getOptions($optionNames = null)
  236. {
  237. $options = [];
  238. if ($optionNames === null) {
  239. $optionNames = $this->optionNames;
  240. }
  241. foreach ($optionNames as $option) {
  242. $converter = 'convert' . ucfirst($option);
  243. $value = method_exists($this, $converter) ? $this->$converter() : $this->$option;
  244. if ($value === null) {
  245. continue;
  246. }
  247. $options[$option] = $value;
  248. }
  249. return $options;
  250. }
  251. /**
  252. * @return \Iterator
  253. */
  254. protected function ensureIterator()
  255. {
  256. if ($this->iterator === null) {
  257. $this->iterator = $this->wrapTraversable($this->ensureCursor());
  258. $this->iterator->rewind();
  259. }
  260. return $this->iterator;
  261. }
  262. /**
  263. * @param \Traversable $traversable
  264. * @return CursorIterator
  265. */
  266. protected function wrapTraversable(\Traversable $traversable)
  267. {
  268. return new CursorIterator($traversable);
  269. }
  270. /**
  271. * @throws \MongoCursorException
  272. */
  273. protected function errorIfOpened()
  274. {
  275. if ($this->cursor === null) {
  276. return;
  277. }
  278. throw new \MongoCursorException('cannot modify cursor after beginning iteration.');
  279. }
  280. /**
  281. * @return array
  282. */
  283. protected function getIterationInfo()
  284. {
  285. $iterationInfo = [
  286. 'started_iterating' => $this->cursor !== null,
  287. ];
  288. if ($this->cursor !== null) {
  289. switch ($this->cursor->getServer()->getType()) {
  290. case \MongoDB\Driver\Server::TYPE_RS_ARBITER:
  291. $typeString = 'ARBITER';
  292. break;
  293. case \MongoDB\Driver\Server::TYPE_MONGOS:
  294. $typeString = 'MONGOS';
  295. break;
  296. case \MongoDB\Driver\Server::TYPE_RS_PRIMARY:
  297. $typeString = 'PRIMARY';
  298. break;
  299. case \MongoDB\Driver\Server::TYPE_RS_SECONDARY:
  300. $typeString = 'SECONDARY';
  301. break;
  302. default:
  303. $typeString = 'STANDALONE';
  304. }
  305. $cursorId = (string) $this->cursor->getId();
  306. $iterationInfo += [
  307. 'id' => (int) $cursorId,
  308. 'at' => $this->position,
  309. 'numReturned' => $this->position, // This can't be obtained from the new cursor
  310. 'server' => sprintf('%s:%d;-;.;%d', $this->cursor->getServer()->getHost(), $this->cursor->getServer()->getPort(), getmypid()),
  311. 'host' => $this->cursor->getServer()->getHost(),
  312. 'port' => $this->cursor->getServer()->getPort(),
  313. 'connection_type_desc' => $typeString,
  314. ];
  315. }
  316. return $iterationInfo;
  317. }
  318. /**
  319. * @throws \Exception
  320. */
  321. protected function notImplemented()
  322. {
  323. throw new \Exception('Not implemented');
  324. }
  325. /**
  326. * Clears the cursor
  327. *
  328. * This is generic but implemented as protected since it's only exposed in MongoCursor
  329. */
  330. protected function reset()
  331. {
  332. $this->startedIterating = false;
  333. $this->cursorNeedsAdvancing = true;
  334. $this->cursor = null;
  335. $this->iterator = null;
  336. $this->storeIteratorState();
  337. }
  338. /**
  339. * @return array
  340. */
  341. public function __sleep()
  342. {
  343. return ['batchSize', 'connection', 'iterator', 'ns', 'optionNames', 'position', 'startedIterating'];
  344. }
  345. /**
  346. * Stores the current cursor element.
  347. *
  348. * This is necessary because hasNext() might advance the iterator but we still
  349. * need to be able to return the current object.
  350. */
  351. protected function storeIteratorState()
  352. {
  353. if (! $this->startedIterating) {
  354. $this->current = null;
  355. $this->key = null;
  356. $this->valid = false;
  357. return null;
  358. }
  359. $this->current = $this->ensureIterator()->current();
  360. $this->key = $this->ensureIterator()->key();
  361. $this->valid = $this->ensureIterator()->valid();
  362. if ($this->current !== null) {
  363. $this->current = TypeConverter::toLegacy($this->current);
  364. }
  365. return $this->current;
  366. }
  367. }