1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Nette;
13:
14: use Nette;
15:
16:
17:
18: 19: 20: 21: 22:
23: final class Callback extends Object
24: {
25:
26: private $cb;
27:
28:
29:
30: 31: 32: 33: 34:
35: public function __construct($t, $m = NULL)
36: {
37: if ($m === NULL) {
38: if (is_string($t)) {
39: $t = explode('::', $t, 2);
40: $this->cb = isset($t[1]) ? $t : $t[0];
41: } elseif (is_object($t)) {
42: $this->cb = $t instanceof \Closure ? $t : array($t, '__invoke');
43: } else {
44: $this->cb = $t;
45: }
46:
47: } else {
48: $this->cb = array($t, $m);
49: }
50:
51: if (!is_callable($this->cb, TRUE)) {
52: throw new InvalidArgumentException("Invalid callback.");
53: }
54: }
55:
56:
57:
58: 59: 60: 61:
62: public function __invoke()
63: {
64: if (!is_callable($this->cb)) {
65: throw new InvalidStateException("Callback '$this' is not callable.");
66: }
67: $args = func_get_args();
68: return call_user_func_array($this->cb, $args);
69: }
70:
71:
72:
73: 74: 75: 76:
77: public function invoke()
78: {
79: if (!is_callable($this->cb)) {
80: throw new InvalidStateException("Callback '$this' is not callable.");
81: }
82: $args = func_get_args();
83: return call_user_func_array($this->cb, $args);
84: }
85:
86:
87:
88: 89: 90: 91: 92:
93: public function invokeArgs(array $args)
94: {
95: if (!is_callable($this->cb)) {
96: throw new InvalidStateException("Callback '$this' is not callable.");
97: }
98: return call_user_func_array($this->cb, $args);
99: }
100:
101:
102:
103: 104: 105: 106: 107:
108: public function invokeNamedArgs(array $args)
109: {
110: $ref = $this->toReflection();
111: if (is_array($this->cb)) {
112: return $ref->invokeNamedArgs(is_object($this->cb[0]) ? $this->cb[0] : NULL, $args);
113: } else {
114: return $ref->invokeNamedArgs($args);
115: }
116: }
117:
118:
119:
120: 121: 122: 123:
124: public function isCallable()
125: {
126: return is_callable($this->cb);
127: }
128:
129:
130:
131: 132: 133: 134:
135: public function getNative()
136: {
137: return $this->cb;
138: }
139:
140:
141:
142: 143: 144: 145:
146: public function toReflection()
147: {
148: if (is_array($this->cb)) {
149: return new Nette\Reflection\Method($this->cb[0], $this->cb[1]);
150: } else {
151: return new Nette\Reflection\GlobalFunction($this->cb);
152: }
153: }
154:
155:
156:
157: 158: 159:
160: public function isStatic()
161: {
162: return is_array($this->cb) ? is_string($this->cb[0]) : is_string($this->cb);
163: }
164:
165:
166:
167: 168: 169:
170: public function __toString()
171: {
172: if ($this->cb instanceof \Closure) {
173: return '{closure}';
174: } elseif (is_string($this->cb) && $this->cb[0] === "\0") {
175: return '{lambda}';
176: } else {
177: is_callable($this->cb, TRUE, $textual);
178: return $textual;
179: }
180: }
181:
182: }
183: