RewindableGenerator.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. */
  26. public function __construct(callable $generator, $count)
  27. {
  28. $this->count = $count;
  29. $this->generator = $generator;
  30. }
  31. /**
  32. * Get an iterator from the generator.
  33. *
  34. * @return \Traversable
  35. */
  36. public function getIterator(): Traversable
  37. {
  38. return ($this->generator)();
  39. }
  40. /**
  41. * Get the total number of tagged services.
  42. *
  43. * @return int
  44. */
  45. public function count(): int
  46. {
  47. if (is_callable($count = $this->count)) {
  48. $this->count = $count();
  49. }
  50. return $this->count;
  51. }
  52. }