Passed
Push — master ( 47e4fd...680194 )
by Alexander
01:28
created

Provider::detach()   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 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace Yiisoft\EventDispatcher\Provider;
4
5
use Psr\EventDispatcher\ListenerProviderInterface;
6
7
/**
8
 * Provider is a listener provider that registers event listeners for interfaces used in callable type-hints
9
 * and gives out a list of handlers by event interface provided for further use with Dispatcher.
10
 *
11
 * ```php
12
 * $provider = new Yiisoft\EventDispatcher\Provider\Provider();
13
 *
14
 * // adding some listeners
15
 * $provider->attach(function (AfterDocumentProcessed $event) {
16
 *    $document = $event->getDocument();
17
 *    // do something with document
18
 * });
19
 * ```
20
 */
21
final class Provider extends AbstractProviderConfigurator implements ListenerProviderInterface
22
{
23
    /**
24
     * @var callable[]
25
     */
26
    private array $listeners = [];
27
28 7
    public function getListenersForEvent(object $event): iterable
29
    {
30 7
        yield from $this->listenersFor(get_class($event));
31 7
        yield from $this->listenersFor(...array_values(class_parents($event)));
32 7
        yield from $this->listenersFor(...array_values(class_implements($event)));
33
    }
34
35
    /**
36
     * Attaches listener to corresponding event based on the type-hint used for the event argument.
37
     *
38
     * Method signature should be the following:
39
     *
40
     * ```
41
     *  function (MyEvent $event): void
42
     * ```
43
     *
44
     * Any callable could be used be it a closure, invokable object or array referencing a class or object.
45
     *
46
     * @param callable $listener
47
     * @param string $eventClassName
48
     */
49 8
    protected function attach(callable $listener, string $eventClassName = ''): void
50
    {
51 8
        if ($eventClassName === '') {
52 7
            $eventClassName = $this->getParameterType($listener);
53
        }
54
55 7
        $this->listeners[$eventClassName][] = $listener;
56
    }
57
58
    /**
59
     * Derives the interface type of the first argument of a callable.
60
     *
61
     * @param callable $callable The callable for which we want the parameter type.
62
     * @return string The interface the parameter is type hinted on.
63
     */
64 7
    private function getParameterType(callable $callable): string
65
    {
66
        // This try-catch is only here to keep OCD linters happy about uncaught reflection exceptions.
67
        try {
68
            switch (true) {
69
                // See note on isClassCallable() for why this must be the first case.
70 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...
71 1
                    $reflect = new \ReflectionClass($callable[0]);
72 1
                    $params = $reflect->getMethod($callable[1])->getParameters();
73 1
                    break;
74 6
                case $this->isFunctionCallable($callable):
75 5
                case $this->isClosureCallable($callable):
76 4
                    $reflect = new \ReflectionFunction($callable);
77 4
                    $params = $reflect->getParameters();
78 4
                    break;
79 2
                case $this->isObjectCallable($callable):
80 1
                    $reflect = new \ReflectionObject($callable[0]);
81 1
                    $params = $reflect->getMethod($callable[1])->getParameters();
82 1
                    break;
83 1
                case $this->isInvokable($callable):
84 1
                    $params = (new \ReflectionMethod($callable, '__invoke'))->getParameters();
85 1
                    break;
86
                default:
87
                    throw new \InvalidArgumentException('Not a recognized type of callable');
88
            }
89
90 7
            $reflectedType = isset($params[0]) ? $params[0]->getType() : null;
91 7
            if ($reflectedType === null) {
92 1
                throw new \InvalidArgumentException('Listeners must declare an object type they can accept.');
93
            }
94 6
            $type = $reflectedType->getName();
95 1
        } catch (\ReflectionException $e) {
96
            throw new \RuntimeException('Type error registering listener.', 0, $e);
97
        }
98
99 6
        return $type;
100
    }
101
102
    /**
103
     * Determines if a callable represents a function.
104
     *
105
     * Or at least a reasonable approximation, since a function name may not be defined yet.
106
     *
107
     * @param callable $callable
108
     * @return True if the callable represents a function, false otherwise.
109
     */
110 6
    private function isFunctionCallable(callable $callable): bool
111
    {
112
        // We can't check for function_exists() because it may be included later by the time it matters.
113 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...
114
    }
115
116
    /**
117
     * Determines if a callable represents a closure/anonymous function.
118
     *
119
     * @param callable $callable
120
     * @return True if the callable represents a closure object, false otherwise.
121
     */
122 5
    private function isClosureCallable(callable $callable): bool
123
    {
124 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...
125
    }
126
127
    /**
128
     * @param callable $callable
129
     * @return True if the callable represents an invokable object, false otherwise.
130
     */
131 1
    private function isInvokable(callable $callable): bool
132
    {
133 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...
134
    }
135
136
    /**
137
     * Determines if a callable represents a method on an object.
138
     *
139
     * @param callable $callable
140
     * @return True if the callable represents a method object, false otherwise.
141
     */
142 2
    private function isObjectCallable(callable $callable): bool
143
    {
144 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...
145
    }
146
147
    /**
148
     * Determines if a callable represents a static class method.
149
     *
150
     * The parameter here is untyped so that this method may be called with an
151
     * array that represents a class name and a non-static method.  The routine
152
     * to determine the parameter type is identical to a static method, but such
153
     * an array is still not technically callable.  Omitting the parameter type here
154
     * allows us to use this method to handle both cases.
155
     *
156
     * Note that this method must therefore be the first in the switch statement
157
     * above, or else subsequent calls will break as the array is not going to satisfy
158
     * the callable type hint but it would pass `is_callable()`.  Because PHP.
159
     *
160
     * @param callable $callable
161
     * @return True if the callable represents a static method, false otherwise.
162
     */
163 7
    private function isClassCallable($callable): bool
164
    {
165 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...
166
    }
167
168
    /**
169
     * @param string ...$eventClassNames
170
     * @return iterable<callable>
171
     */
172 7
    private function listenersFor(string ...$eventClassNames): iterable
173
    {
174 7
        foreach ($eventClassNames as $eventClassName) {
175 7
            if (isset($this->listeners[$eventClassName])) {
176 7
                yield from $this->listeners[$eventClassName];
177
            }
178
        }
179
    }
180
}
181