<?php
class CollectionLimiter {
private $limit;
private $collection;
public function __construct(int $limit, iterable $collection) {
$this->limit = $limit;
$this->collection = $collection;
}
public function getNext(): ?mixed {
$count = 0;
foreach ($this->collection as $item) {
if ($count >= $this->limit) {
return null; // Limit reached
}
$count++;
}
return $this->collection[$count - 1]; // Return remaining item
}
public function hasNext(): bool {
$count = 0;
foreach ($this->collection as $item) {
if ($count >= $this->limit) {
return false;
}
$count++;
}
return true;
}
public function reset(): void {
// Reset the internal state. Important if the collection is reused.
$this->collection = $this->collection; //re-assign the collection
$this->limit = $this->limit;
}
}
//Example Usage:
/*
$data = range(1, 10);
$limiter = new CollectionLimiter(5, $data);
foreach ($limiter as $item) {
echo $item . " ";
}
echo "\n";
$limiter->reset();
foreach ($limiter as $item) {
echo $item . " ";
}
echo "\n";
*/
?>
Add your comment