Skip to content

Instantly share code, notes, and snippets.

@sergiors
Last active July 4, 2016 20:18
Show Gist options
  • Save sergiors/abe9a46e376466f81fb8f1482f55a3b3 to your computer and use it in GitHub Desktop.
Save sergiors/abe9a46e376466f81fb8f1482f55a3b3 to your computer and use it in GitHub Desktop.
$upper = pipe('strtoupper');
$rev = $upper->pipe('strrev');

echo $upper('hello');
echo $rev('Hello');
echo pipe('strtoupper', 'strrev')('hello'); 
<?php
interface PipeInterface
{
public function pipe(callable ...$callbacks): PipeInterface;
public function process($payload);
}
function pipe(callable ...$callbacks)
{
return new class(...$callbacks) implements PipeInterface
{
private $callbacks;
public function __construct(callable ...$callbacks)
{
$this->callbacks = $callbacks;
}
public function pipe(callable ...$callbacks): PipeInterface
{
return pipe(...array_merge($this->callbacks, $callbacks));
}
public function process($payload)
{
return array_reduce($this->callbacks, function ($payload, $callback) {
return call_user_func($callback, $payload);
}, $payload);
}
public function __invoke($payload)
{
return $this->process($payload);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment