1 | <?php |
||
5 | class Trampoline |
||
6 | { |
||
7 | /** @var callable $f */ |
||
8 | private $f; |
||
9 | |||
10 | /** @var array $args */ |
||
11 | private $args; |
||
12 | |||
13 | /** |
||
14 | * @param callable $f |
||
15 | * @param array $args |
||
16 | */ |
||
17 | protected function __construct(callable $f, array $args = array()) |
||
22 | |||
23 | /** |
||
24 | * Invoke the stored function with the stored arguments. |
||
25 | * |
||
26 | * @return mixed |
||
27 | */ |
||
28 | public function __invoke() |
||
32 | |||
33 | /** |
||
34 | * Create a new trampoline instance for the given function and arguments. |
||
35 | * |
||
36 | * @param callable $f |
||
37 | * @param array ...$args |
||
38 | * @return static|callable |
||
39 | */ |
||
40 | public static function bounce(callable $f, ...$args) |
||
44 | |||
45 | /** |
||
46 | * Run a callable or a Trampoline until it gets to the final result |
||
47 | * (ie: not a Trampoline instance) |
||
48 | * |
||
49 | * @param callable|Trampoline $f |
||
50 | * @param array ...$args |
||
51 | * @return mixed |
||
52 | */ |
||
53 | public static function run($f, ...$args) |
||
54 | { |
||
55 | 1 | if($f instanceof self) { |
|
56 | 1 | $return = $f; |
|
57 | 1 | } else if(is_callable($f)) { |
|
58 | 1 | $return = call_user_func_array($f, $args); |
|
59 | } else { |
||
60 | 1 | throw new \RuntimeException('Expected a callable or an instance of Trampoline.'); |
|
61 | } |
||
62 | |||
63 | 1 | while($return instanceof self) { |
|
64 | 1 | $return = $return(); |
|
65 | } |
||
66 | |||
67 | 1 | return $return; |
|
68 | } |
||
69 | |||
70 | /** |
||
71 | * Helper function to easily run a callable as a Trampoline. |
||
72 | * |
||
73 | * @param string $name |
||
74 | * @param array $arguments |
||
75 | * @return mixed |
||
76 | */ |
||
77 | public static function __callStatic($name, $arguments) |
||
81 | } |