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