PDOStatementSourceIterator.php 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Exporter\Source;
  11. use Exporter\Exception\InvalidMethodCallException;
  12. class PDOStatementSourceIterator implements SourceIteratorInterface
  13. {
  14. protected $statement;
  15. protected $current;
  16. protected $position;
  17. protected $rewinded;
  18. /**
  19. * @param \PDOStatement $statement
  20. */
  21. public function __construct(\PDOStatement $statement)
  22. {
  23. $this->statement = $statement;
  24. $this->position = 0;
  25. $this->rewinded = false;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function current()
  31. {
  32. return $this->current;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function next()
  38. {
  39. $this->current = $this->statement->fetch(\PDO::FETCH_ASSOC);
  40. $this->position++;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function key()
  46. {
  47. return $this->position;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function valid()
  53. {
  54. return is_array($this->current);
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function rewind()
  60. {
  61. if ($this->rewinded) {
  62. throw new InvalidMethodCallException('Cannot rewind a PDOStatement');
  63. }
  64. $this->current = $this->statement->fetch(\PDO::FETCH_ASSOC);
  65. $this->rewinded = true;
  66. }
  67. }