Passed
Pull Request — master (#31)
by Alexander
03:39 queued 02:03
created

ListenerCollection::isInvokable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Yiisoft\EventDispatcher\Provider;
4
5
/**
6
 * Listener collection stores listeners and is used to configure provider.
7
 *
8
 * @see Provider
9
 */
10
final class ListenerCollection
11
{
12
    /**
13
     * @var callable[]
14
     */
15
    private array $listeners = [];
16
17
    /**
18
     * @param string ...$eventClassNames
19
     * @return iterable<callable>
20
     */
21 7
    public function getForEvents(string ...$eventClassNames): iterable
22
    {
23 7
        foreach ($eventClassNames as $eventClassName) {
24 7
            if (isset($this->listeners[$eventClassName])) {
25 7
                yield from $this->listeners[$eventClassName];
26
            }
27
        }
28 7
    }
29
30
    /**
31
     * Attaches listener to corresponding event based on the type-hint used for the event argument.
32
     *
33
     * Method signature should be the following:
34
     *
35
     * ```
36
     *  function (MyEvent $event): void
37
     * ```
38
     *
39
     * Any callable could be used be it a closure, invokable object or array referencing a class or object.
40
     *
41
     * @param callable $listener
42
     * @param string $eventClassName
43
     * @return self
44
     */
45 8
    public function add(callable $listener, string $eventClassName = ''): self
46
    {
47 8
        $new = clone $this;
48
49 8
        if ($eventClassName === '') {
50 7
            $eventClassName = $this->getParameterType($listener);
51
        }
52
53 7
        $new->listeners[$eventClassName][] = $listener;
54 7
        return $new;
55
    }
56
57
    /**
58
     * Derives the interface type of the first argument of a callable.
59
     *
60
     * @suppress PhanUndeclaredMethod
61
     *
62
     * @param callable $callable The callable for which we want the parameter type.
63
     * @return string The interface the parameter is type hinted on.
64
     */
65 7
    private function getParameterType(callable $callable): string
66
    {
67
        // This try-catch is only here to keep OCD linters happy about uncaught reflection exceptions.
68
        try {
69
            switch (true) {
70
                // See note on isClassCallable() for why this must be the first case.
71 7
                case $this->isClassCallable($callable):
0 ignored issues
show
Unused Code introduced by
$this->isClassCallable($callable) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
72 1
                    $reflect = new \ReflectionClass($callable[0]);
73 1
                    $params = $reflect->getMethod($callable[1])->getParameters();
74 1
                    break;
75 6
                case $this->isFunctionCallable($callable):
76 5
                case $this->isClosureCallable($callable):
77 4
                    $reflect = new \ReflectionFunction($callable);
78 4
                    $params = $reflect->getParameters();
79 4
                    break;
80 2
                case $this->isObjectCallable($callable):
81 1
                    $reflect = new \ReflectionObject($callable[0]);
82 1
                    $params = $reflect->getMethod($callable[1])->getParameters();
83 1
                    break;
84 1
                case $this->isInvokable($callable):
85 1
                    $params = (new \ReflectionMethod($callable, '__invoke'))->getParameters();
86 1
                    break;
87
                default:
88
                    throw new \InvalidArgumentException('Not a recognized type of callable');
89
            }
90
91 7
            $reflectedType = isset($params[0]) ? $params[0]->getType() : null;
92 7
            if ($reflectedType === null) {
93 1
                throw new \InvalidArgumentException('Listeners must declare an object type they can accept.');
94
            }
95 6
            $type = $reflectedType->getName();
96 1
        } catch (\ReflectionException $e) {
97
            throw new \RuntimeException('Type error registering listener.', 0, $e);
98
        }
99
100 6
        return $type;
101
    }
102
103
    /**
104
     * Determines if a callable represents a function.
105
     *
106
     * Or at least a reasonable approximation, since a function name may not be defined yet.
107
     *
108
     * @param callable $callable
109
     * @return True if the callable represents a function, false otherwise.
110
     */
111 6
    private function isFunctionCallable(callable $callable): bool
112
    {
113
        // We can't check for function_exists() because it may be included later by the time it matters.
114 6
        return is_string($callable);
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_string($callable) returns the type boolean which is incompatible with the documented return type true.
Loading history...
115
    }
116
117
    /**
118
     * Determines if a callable represents a closure/anonymous function.
119
     *
120
     * @param callable $callable
121
     * @return True if the callable represents a closure object, false otherwise.
122
     */
123 5
    private function isClosureCallable(callable $callable): bool
124
    {
125 5
        return $callable instanceof \Closure;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $callable instanceof Closure returns the type boolean which is incompatible with the documented return type true.
Loading history...
126
    }
127
128
    /**
129
     * @param callable $callable
130
     * @return True if the callable represents an invokable object, false otherwise.
131
     */
132 1
    private function isInvokable(callable $callable): bool
133
    {
134 1
        return is_object($callable);
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_object($callable) returns the type boolean which is incompatible with the documented return type true.
Loading history...
135
    }
136
137
    /**
138
     * Determines if a callable represents a method on an object.
139
     *
140
     * @param callable $callable
141
     * @return True if the callable represents a method object, false otherwise.
142
     */
143 2
    private function isObjectCallable(callable $callable): bool
144
    {
145 2
        return is_array($callable) && is_object($callable[0]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_array($callabl...is_object($callable[0]) returns the type boolean which is incompatible with the documented return type true.
Loading history...
146
    }
147
148
    /**
149
     * Determines if a callable represents a static class method.
150
     *
151
     * The parameter here is untyped so that this method may be called with an
152
     * array that represents a class name and a non-static method.  The routine
153
     * to determine the parameter type is identical to a static method, but such
154
     * an array is still not technically callable.  Omitting the parameter type here
155
     * allows us to use this method to handle both cases.
156
     *
157
     * Note that this method must therefore be the first in the switch statement
158
     * above, or else subsequent calls will break as the array is not going to satisfy
159
     * the callable type hint but it would pass `is_callable()`.  Because PHP.
160
     *
161
     * @param callable $callable
162
     * @return True if the callable represents a static method, false otherwise.
163
     */
164 7
    private function isClassCallable($callable): bool
165
    {
166 7
        return is_array($callable) && is_string($callable[0]) && class_exists($callable[0]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_array($callabl...ss_exists($callable[0]) returns the type boolean which is incompatible with the documented return type true.
Loading history...
167
    }
168
}
169