Skip to content

Instantly share code, notes, and snippets.

@tamakiii
Last active October 26, 2015 16:56
Show Gist options
  • Save tamakiii/cbb3444c37da1a3510db to your computer and use it in GitHub Desktop.
Save tamakiii/cbb3444c37da1a3510db to your computer and use it in GitHub Desktop.
<?php
interface TraversableOperatorInterface
{
/**
* @param Traversable $rows
* @param callable $callable
* @return Generator
*/
public function append(Traversable $rows, callable $callable);
/**
* @param Traversable $rows
* @param callable $callable
* @return Generator
*/
public function map(Traversable $rows, callable $callable);
}
class TraversableOperator
{
/**
* @param Traversable $rows
* @param callable $callable (return Traversable)
* @return Generator
*/
public function append(Traversable $rows, callable $callable)
{
foreach ($rows as $key => $row) {
$result = call_user_func($callable, $row);
if (!$result instanceof Traversable) {
throw new \LogicException('Callable must return array or Traversable:' . gettype($result));
}
yield $key => array_merge($row, iterator_to_array($result));
}
}
/**
* @param Traversable $rows
* @param callable $callable
* @return Generator
*/
public function map(array $rows, callable $callable)
{
foreach ($rows as $key => $row) {
yield $key => array_map($callable, $row);
}
}
}
class Calculator
{
/**
* @param array $row
* @return Traversable
*/
public function calculate(array $row)
{
yield 'rate' => $row['click'] / $row['imp'];
}
}
$rows = [
0 => ['id' => 1, 'imp' => 100, 'click' => 0],
2 => ['id' => 2, 'imp' => 200, 'click' => 1],
4 => ['id' => 3, 'imp' => 300, 'click' => 2],
8 => ['id' => 4, 'imp' => 400, 'click' => 4],
16 => ['id' => 5, 'imp' => 500, 'click' => 8],
];
$operator = new TraversableOperator;
$rows = new ArrayIterator($rows);
// naming
$rows = $operator->append($rows, function(array $row) {
yield 'name' => "id={$row['id']}";
});
// calculating
$rows = $operator->append($rows, [new Calculator, 'calculate']);
var_dump(iterator_to_array($rows));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment