1. <?php
  2. class CollectionLimiter {
  3. private $limit;
  4. private $collection;
  5. public function __construct(int $limit, iterable $collection) {
  6. $this->limit = $limit;
  7. $this->collection = $collection;
  8. }
  9. public function getNext(): ?mixed {
  10. $count = 0;
  11. foreach ($this->collection as $item) {
  12. if ($count >= $this->limit) {
  13. return null; // Limit reached
  14. }
  15. $count++;
  16. }
  17. return $this->collection[$count - 1]; // Return remaining item
  18. }
  19. public function hasNext(): bool {
  20. $count = 0;
  21. foreach ($this->collection as $item) {
  22. if ($count >= $this->limit) {
  23. return false;
  24. }
  25. $count++;
  26. }
  27. return true;
  28. }
  29. public function reset(): void {
  30. // Reset the internal state. Important if the collection is reused.
  31. $this->collection = $this->collection; //re-assign the collection
  32. $this->limit = $this->limit;
  33. }
  34. }
  35. //Example Usage:
  36. /*
  37. $data = range(1, 10);
  38. $limiter = new CollectionLimiter(5, $data);
  39. foreach ($limiter as $item) {
  40. echo $item . " ";
  41. }
  42. echo "\n";
  43. $limiter->reset();
  44. foreach ($limiter as $item) {
  45. echo $item . " ";
  46. }
  47. echo "\n";
  48. */
  49. ?>

Add your comment