Skip to content

Instantly share code, notes, and snippets.

@maemichi-monosense
Last active June 4, 2018 05:52
Show Gist options
  • Select an option

  • Save maemichi-monosense/2e56883c4a4d971f14a8d7fb4ed9f18b to your computer and use it in GitHub Desktop.

Select an option

Save maemichi-monosense/2e56883c4a4d971f14a8d7fb4ed9f18b to your computer and use it in GitHub Desktop.
PHP Generator toybox
<?php
/**
* @see http://blog.kevingomez.fr/2016/02/26/efficiently-creating-data-chunks-in-php/
*
* @param Iterator $iterable
* @param int $size > 0
*
* @return Generator {int => Generator}
*/
function iter_chunk(\Iterator $iterable, $size): \Iterator
{
if (!($size > 0)) {
throw new InvalidArgumentException('Size must be positive number');
}
$chunker = function (\Iterator $iterable, $size) {
$i = 0;
while ($size-- > 0 && $iterable->valid()) {
yield $i++ => $iterable->current();
$iterable->next();
}
};
while ($iterable->valid()) {
yield $chunker($iterable, $size);
}
}
// main
$main = isset($argv[0]) && realpath($argv[0]) === __FILE__;
if ($main) {
$iter = new \SplFileObject('php://stdin');
$iter->setFlags(\SplFileObject::DROP_NEW_LINE);
foreach (iter_chunk($iter, 3) as $i => $ns) {
echo 'chunk=' . $i++ . PHP_EOL;
var_dump(iterator_to_array($ns));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment