I have implemented a collection class that stores a single type of value.
At the moment it is immutable.
abstract class Collection implements Iterator
{
/** @var int */
protected $position = 0;
/** @var array */
private $items = [];
public function next()
{
++$this->position;
}
public function key()
{
return $this->position;
}
public function valid()
{
return isset($this->items[$this->position]);
}
public function rewind()
{
$this->position = 0;
}
protected function add($item)
{
return $this->items[] = $item;
}
protected function get($index)
{
return $this->items[$index];
}
}
DateTimeIterator
guarantees that when iterated over it will only return the specified type.
interface DateTimeIterator extends Iterator
{
public function current(): DateTimeInterface;
}
The constructor of DateTimeCollection
ensures that the collection only stores values that implement DateTimeInterface
.
class DateTimeCollection extends Collection implements DateTimeIterator
{
public function __construct(iterable $values = [])
{
foreach ($values as $value) {
if (!$value instanceof DateTimeInterface) {
throw new TypeError('DateTimeCollection only accepts ' .
'items that implement DateTimeInterface');
}
$this->add($value);
}
}
public function current(): DateTimeInterface
{
return $this->get($this->key());
}
}