File: CallbackHandler.php

package info (click to toggle)
zendframework 1.12.9%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 133,584 kB
  • sloc: xml: 1,311,829; php: 570,173; sh: 170; makefile: 125; sql: 121
file content (301 lines) | stat: -rw-r--r-- 8,940 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Stdlib
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * CallbackHandler
 *
 * A handler for a event, event, filterchain, etc. Abstracts PHP callbacks,
 * primarily to allow for lazy-loading and ensuring availability of default
 * arguments (currying).
 *
 * @category   Zend
 * @package    Zend_Stdlib
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Stdlib_CallbackHandler
{
    /**
     * @var string|array PHP callback to invoke
     */
    protected $callback;

    /**
     * Did an error occur when testing the validity of the callback?
     * @var bool
     */
    protected $error = false;

    /**
     * Callback metadata, if any
     * @var array
     */
    protected $metadata;

    /**
     * Constructor
     * 
     * @param  string $event Event to which slot is subscribed
     * @param  string|array|object $callback PHP callback 
     * @param  array $options Options used by the callback handler (e.g., priority)
     * @return void
     */
    public function __construct($callback, array $metadata = array())
    {
        $this->metadata  = $metadata;
        $this->registerCallback($callback);
    }

    /**
     * Error handler
     *
     * Used by registerCallback() when calling is_callable() to capture engine warnings.
     * 
     * @param  int $errno 
     * @param  string $errstr 
     * @return void
     */
    public function errorHandler($errno, $errstr)
    {
        $this->error = true;
    }

    /**
     * Registers the callback provided in the constructor
     *
     * If you have pecl/weakref {@see http://pecl.php.net/weakref} installed, 
     * this method provides additional behavior.
     *
     * If a callback is a functor, or an array callback composing an object 
     * instance, this method will pass the object to a WeakRef instance prior
     * to registering the callback.
     * 
     * @param  Callable $callback 
     * @return void
     */
    protected function registerCallback($callback)
    {
        set_error_handler(array($this, 'errorHandler'), E_STRICT);
        $callable = is_callable($callback);
        restore_error_handler();
        if (!$callable || $this->error) {
            require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php';
            throw new Zend_Stdlib_Exception_InvalidCallbackException('Invalid callback provided; not callable');
        }

        // If pecl/weakref is not installed, simply store the callback and return
        if (!class_exists('WeakRef')) {
            $this->callback = $callback;
            return;
        }

        // If WeakRef exists, we want to use it.

        // If we have a non-closure object, pass it to WeakRef, and then
        // register it.
        if (is_object($callback) && !$callback instanceof Closure) {
            $this->callback = new WeakRef($callback);
            return;
        }

        // If we have a string or closure, register as-is
        if (!is_array($callback)) {
            $this->callback = $callback;
            return;
        }

        list($target, $method) = $callback;

        // If we have an array callback, and the first argument is not an 
        // object, register as-is
        if (!is_object($target)) {
            $this->callback = $callback;
            return;
        }

        // We have an array callback with an object as the first argument;
        // pass it to WeakRef, and then register the new callback
        $target = new WeakRef($target);
        $this->callback = array($target, $method);
    }

    /**
     * Retrieve registered callback
     * 
     * @return Callable
     */
    public function getCallback()
    {
        $callback = $this->callback;

        // String callbacks -- simply return
        if (is_string($callback)) {
            return $callback;
        }

        // WeakRef callbacks -- pull it out of the object and return it
        if ($callback instanceof WeakRef) {
            return $callback->get();
        }

        // Non-WeakRef object callback -- return it
        if (is_object($callback)) {
            return $callback;
        }

        // Array callback with WeakRef object -- retrieve the object first, and 
        // then return
        list($target, $method) = $callback;
        if ($target instanceof WeakRef) {
            return array($target->get(), $method);
        }

        // Otherwise, return it
        return $callback;
    }

    /**
     * Invoke handler
     * 
     * @param  array $args Arguments to pass to callback
     * @return mixed
     */
    public function call(array $args = array())
    {
        $callback = $this->getCallback();

        $isPhp54 = version_compare(PHP_VERSION, '5.4.0rc1', '>=');

        if ($isPhp54 && is_string($callback)) {
            $this->validateStringCallbackFor54($callback);
        }

        // Minor performance tweak; use call_user_func() until > 3 arguments 
        // reached
        switch (count($args)) {
            case 0:
                if ($isPhp54) {
                    return $callback();
                }
                return call_user_func($callback);
            case 1:
                if ($isPhp54) {
                    return $callback(array_shift($args));
                }
                return call_user_func($callback, array_shift($args));
            case 2:
                $arg1 = array_shift($args);
                $arg2 = array_shift($args);
                if ($isPhp54) {
                    return $callback($arg1, $arg2);
                }
                return call_user_func($callback, $arg1, $arg2);
            case 3:
                $arg1 = array_shift($args);
                $arg2 = array_shift($args);
                $arg3 = array_shift($args);
                if ($isPhp54) {
                    return $callback($arg1, $arg2, $arg3);
                }
                return call_user_func($callback, $arg1, $arg2, $arg3);
            default:
                return call_user_func_array($callback, $args);
        }
    }

    /**
     * Invoke as functor
     * 
     * @return mixed
     */
    public function __invoke()
    {
        return $this->call(func_get_args());
    }

    /**
     * Get all callback metadata
     * 
     * @return array
     */
    public function getMetadata()
    {
        return $this->metadata;
    }

    /**
     * Retrieve a single metadatum
     * 
     * @param  string $name 
     * @return mixed
     */
    public function getMetadatum($name)
    {
        if (array_key_exists($name, $this->metadata)) {
            return $this->metadata[$name];
        }
        return null;
    }

    /**
     * Validate a static method call
     *
     * Validates that a static method call in PHP 5.4 will actually work
     * 
     * @param  string $callback 
     * @return true
     * @throws Zend_Stdlib_Exception_InvalidCallbackException if invalid
     */
    protected function validateStringCallbackFor54($callback)
    {
        if (!strstr($callback, '::')) {
            return true;
        }

        list($class, $method) = explode('::', $callback, 2);

        if (!class_exists($class)) {
            require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php';
            throw new Zend_Stdlib_Exception_InvalidCallbackException(sprintf(
                'Static method call "%s" refers to a class that does not exist',
                $callback
            ));
        }

        $r = new ReflectionClass($class);
        if (!$r->hasMethod($method)) {
            require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php';
            throw new Zend_Stdlib_Exception_InvalidCallbackException(sprintf(
                'Static method call "%s" refers to a method that does not exist',
                $callback
            ));
        }
        $m = $r->getMethod($method);
        if (!$m->isStatic()) {
            require_once 'Zend/Stdlib/Exception/InvalidCallbackException.php';
            throw new Zend_Stdlib_Exception_InvalidCallbackException(sprintf(
                'Static method call "%s" refers to a method that is not static',
                $callback
            ));
        }

        return true;
    }
}