CursorIterator.php 802 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter;
  3. use IteratorIterator;
  4. use MongoDB\BSON\ObjectID;
  5. use Traversable;
  6. use ReturnTypeWillChange;
  7. /**
  8. * @internal
  9. */
  10. final class CursorIterator extends IteratorIterator
  11. {
  12. /** @var bool */
  13. private $useIdAsKey;
  14. public function __construct(Traversable $iterator, $useIdAsKey = false)
  15. {
  16. parent::__construct($iterator);
  17. $this->useIdAsKey = $useIdAsKey;
  18. }
  19. #[ReturnTypeWillChange]
  20. public function key()
  21. {
  22. if (!$this->useIdAsKey) {
  23. return parent::key();
  24. }
  25. $current = $this->current();
  26. if (!isset($current->_id) || (is_object($current->_id) && !$current->_id instanceof ObjectID)) {
  27. return parent::key();
  28. }
  29. return (string) $current->_id;
  30. }
  31. }