Passed
Pull Request — master (#14)
by Alexander
01:31
created

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