RewindableGenerator.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Illuminate\Container;
  3. use Countable;
  4. use IteratorAggregate;
  5. use Traversable;
  6. class RewindableGenerator implements Countable, IteratorAggregate
  7. {
  8. /**
  9. * The generator callback.
  10. *
  11. * @var callable
  12. */
  13. protected $generator;
  14. /**
  15. * The number of tagged services.
  16. *
  17. * @var callable|int
  18. */
  19. protected $count;
  20. /**
  21. * Create a new generator instance.
  22. *
  23. * @param callable $generator
  24. * @param callable|int $count
  25. * @return void
  26. */
  27. public function __construct(callable $generator, $count)
  28. {
  29. $this->count = $count;
  30. $this->generator = $generator;
  31. }
  32. /**
  33. * Get an iterator from the generator.
  34. *
  35. * @return \Traversable
  36. */
  37. public function getIterator(): Traversable
  38. {
  39. return ($this->generator)();
  40. }
  41. /**
  42. * Get the total number of tagged services.
  43. *
  44. * @return int
  45. */
  46. public function count(): int
  47. {
  48. if (is_callable($count = $this->count)) {
  49. $this->count = $count();
  50. }
  51. return $this->count;
  52. }
  53. }