Skip to content

Instantly share code, notes, and snippets.

@schmengler
Created June 2, 2016 09:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmengler/e3bb832e9a8355e62ed6a377729128db to your computer and use it in GitHub Desktop.
Save schmengler/e3bb832e9a8355e62ed6a377729128db to your computer and use it in GitHub Desktop.
Collections with PHP 5.5 Generators
<?php
// PoC for collection pipeleines with improved memory footprint
// requires php 5.5 >= 5.5.24
// or php 5.6 >= 5.6.8
// or php 7
//
// see: https://bugs.php.net/bug.php?id=69221
class Collection extends \IteratorIterator {
public static function fromArray(array $array)
{
return new static(new \ArrayIterator($array));
}
public static function fromGenerator(callable $callback)
{
$generator = $callback();
if (! $generator instanceof \Generator) {
throw new \InvalidArgumentException('Callback did not return a generator');
}
return new static($generator);
}
public function filter(callable $callback)
{
return self::fromGenerator(function() use ($callback) {
foreach ($this->getInnerIterator() as $key => $value) {
if ($callback($value, $key)) {
yield $key => $value;
}
}
});
}
public function map(callable $callback)
{
return self::fromGenerator(function() use ($callback) {
foreach ($this->getInnerIterator() as $key => $value) {
yield $key => $callback($value);
}
});
}
public function each(callable $callback)
{
foreach ($this->getInnerIterator() as $key => $value) {
$callback($value, $key);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment