Created
December 2, 2011 09:54
-
-
Save katzchang/1422588 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Curry | |
{ | |
protected $callback, $bind; | |
protected function __construct($callback, Array $bind) | |
{ | |
if(!is_callable($callback)) throw new InvalidArgumentException('$callback must be callable'); | |
list($this->callback, $this->bind) = func_get_args(); | |
} | |
static function make($callback, Array $bind) | |
{ | |
return $bind ? array(new self($callback, $bind), 'invoke') : $callback; | |
} | |
function invoke() | |
{ | |
$args = func_get_args(); | |
$args = array_merge($this->bind, $args); | |
return call_user_func_array($this->callback, $args); | |
} | |
} | |
class Quotation | |
{ | |
protected $obj; | |
function __construct($obj) | |
{ | |
$this->obj = $obj; | |
} | |
function __get($name) | |
{ | |
return array($this->obj, $name); | |
} | |
function __call($name, $args) | |
{ | |
return Curry::make($this->{$name}, $args); | |
} | |
} | |
function quote($obj) | |
{ | |
return new Quotation($obj); | |
} | |
function callee() | |
{ | |
list(, $frame) = debug_backtrace() + array(1 => false); | |
if (!$frame) throw new BadFunctionCallException('You must call in function'); | |
$callback = isset($frame['object']) ? array($frame['object'], $frame['function']) : | |
(isset($frame['class']) ? array($frame['class'], $frame['function']) : | |
$frame['function']); | |
$args = func_get_args(); | |
return $args ? Curry::make($callback, $args) : $callback; | |
} | |
function method($name) | |
{ | |
list(, $frame) = debug_backtrace() + array(1 => false); | |
if (!isset($frame['class'])) throw new BadFunctionCallException('You must call in class method'); | |
$callback = array(isset($frame['object']) ? $frame['object'] : $frame['class'], $name); | |
$args = func_get_args(); | |
array_shift($args); | |
return $args ? Curry::make($callback, $args) : $callback; | |
} | |
function bind($callback) | |
{ | |
$args = func_get_args(); | |
array_shift($args); | |
return Curry::make($callback, $args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment