SafeCallable::call()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 1
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace uuf6429\ExpressionLanguage;
4
5
use RuntimeException;
6
7
/**
8
 * A wrapper for an anonymous function.
9
 * We do not return anonymous functions directly for security reason, to avoid
10
 * calling arbitrary functions by returning arrays containing class/method or
11
 * string function names. From the userland, one can still get access to the
12
 * anonymous function using the various public methods.
13
 *
14
 * @author Christian Sciberras <[email protected]>
15
 */
16
class SafeCallable
17
{
18
    protected $callback;
19
20
    /**
21
     * Constructor.
22
     *
23 4
     * @param callable $callback The target callback
24
     */
25 4
    public function __construct(callable $callback)
26 4
    {
27
        $this->callback = $callback;
28
    }
29
30
    /**
31 5
     * @return callable
32
     */
33 5
    public function getCallback(): callable
34
    {
35
        return $this->callback;
36
    }
37
38
    /**
39
     * Call the callback with the provided arguments and returns result.
40
     *
41
     * @return mixed
42
     */
43
    public function call()
44
    {
45
        return $this->callArray(func_get_args());
46
    }
47
48
    /**
49
     * Call the callback with the provided arguments and returns result.
50
     *
51
     * @param array $arguments
52
     *
53 4
     * @return mixed
54
     */
55 4
    public function callArray(array $arguments)
56
    {
57 4
        $callback = $this->getCallback();
58 3
59 4
        return count($arguments)
60
            ? call_user_func_array($callback, $arguments)
61
            : $callback();
62
    }
63
64
    public function __invoke()
65
    {
66
        throw new RuntimeException('Callback wrapper cannot be invoked, use $wrapper->getCallback() instead.');
67
    }
68
}
69