Skip to content

Instantly share code, notes, and snippets.

@m4rw3r
Created November 16, 2013 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m4rw3r/7504106 to your computer and use it in GitHub Desktop.
Save m4rw3r/7504106 to your computer and use it in GitHub Desktop.
<?php
class F
{
protected $f;
protected $params = array();
public function __construct(callable $c, array $params = null)
{
$this->f = $c;
if($params !== null)
{
$this->params = $params;
}
else {
$ref = self::callableReflection($c);
foreach($ref->getParameters() as $p) {
$this->params[] = [
'optional' => $p->isOptional(),
'name' => $p->getName()
];
}
}
}
public function __invoke()
{
return call_user_func_array($this->f, func_get_args());
}
public function getParameters()
{
return $this->params;
}
public function compose(F $g)
{
return new F(function() use($g) {
return $this(call_user_func_array($g, func_get_args()));
}, $g->getParameters());
}
public static function callableReflection(callable $callable)
{
if(is_array($callable) && count($callable) === 2) {
return new ReflectionMethod(array_shift($callable), array_shift($callable));
}
elseif(is_string($callable) && strpos($callable, ':') !== false) {
return new ReflectionMethod($callable);
}
elseif(is_object($callable)) {
return new ReflectionMethod($callable, '__invoke');
}
else {
return new ReflectionFunction($callable);
}
}
}
$f = new F(function($a) {
return $a.'bar';
});
var_dump($f('foo'));
$g = new F(function($a) {
return strtoupper($a);
});
var_dump($g('test'));
$h = $f->compose($g);
var_dump($h('foo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment