Skip to content

Instantly share code, notes, and snippets.

@jackdpeterson
Created July 30, 2018 23:43
Show Gist options
  • Save jackdpeterson/5156e15f96778104496149250f33d4d8 to your computer and use it in GitHub Desktop.
Save jackdpeterson/5156e15f96778104496149250f33d4d8 to your computer and use it in GitHub Desktop.
Sample immutable Typed collection
<?php
final class ImageCollection implements \Iterator, \JsonSerializable, \Countable
{
private $data;
public function __construct(array $values)
{
$this->data = (function (Image ...$values) {
return $values;
}) (...$values);
}
/**
* @return Image|boolean
*/
public function current()
{
return current($this->data);
}
public function next()
{
$var = next($this->data);
return $var;
}
public function key()
{
return key($this->data);
}
public function valid(): bool
{
$key = key($this->data);
return ($key !== null && $key !== false);
}
public function rewind()
{
reset($this->data);
}
public function jsonSerialize()
{
$out = [];
/**
* @var Image $datum
*/
foreach ($this->data as $datum) {
array_push($out, $datum->jsonSerialize());
}
return $out;
}
public function count()
{
return (int)count($this->data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment