Created
June 2, 2016 09:20
-
-
Save schmengler/e3bb832e9a8355e62ed6a377729128db to your computer and use it in GitHub Desktop.
Collections with PHP 5.5 Generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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