Created
November 16, 2013 19:18
-
-
Save m4rw3r/7504106 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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