CursorIterator.php 748 B

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