AbstractCursor.php 11 KB

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