Completed
Branch master (7b578f)
by Ivannis Suárez
02:27
created

EventDispatcher.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * This file is part of the Cubiche package.
5
 *
6
 * Copyright (c) Cubiche
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace Cubiche\Core\EventDispatcher;
12
13
use Cubiche\Core\Collections\ArrayCollection;
14
use Cubiche\Core\Collections\SortedArrayCollection;
15
use Cubiche\Core\Comparable\Comparator;
16
use Cubiche\Core\Comparable\ReverseComparator;
17
18
/**
19
 * EventDispatcher class.
20
 *
21
 * @author Ivannis Suárez Jerez <[email protected]>
22
 */
23
class EventDispatcher implements EventDispatcherInterface
24
{
25
    /**
26
     * @var ArrayCollection
27
     */
28
    protected $listeners;
29
30
    /**
31
     * EventDispatcher constructor.
32
     */
33
    public function __construct()
34
    {
35
        $this->listeners = new ArrayCollection();
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function dispatch($event)
42
    {
43
        $event = $this->ensureEvent($event);
44
45
        $eventName = $event->name();
46
        if ($listeners = $this->listeners($eventName)) {
47
            $this->doDispatch($listeners, $event);
0 ignored issues
show
$listeners is of type array, but the function expects a object<Cubiche\Core\Coll...\SortedArrayCollection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
48
        }
49
50
        return $event;
51
    }
52
53
    /**
54
     * Ensure event input is of type EventInterface or convert it.
55
     *
56
     * @param string|EventInterface $event
57
     *
58
     * @throws InvalidArgumentException
59
     *
60
     * @return EventInterface
61
     */
62
    public function ensureEvent($event)
63
    {
64
        if (is_string($event)) {
65
            return Event::named($event);
66
        }
67
68
        if (!$event instanceof EventInterface) {
69
            throw new \InvalidArgumentException(
70
                sprintf(
71
                    'Events should be provides as %s instances or string, received type: %s',
72
                    EventInterface::class,
73
                    gettype($event)
74
                )
75
            );
76
        }
77
78
        return $event;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function listeners($eventName = null)
85
    {
86
        if (null !== $eventName) {
87
            if (!$this->listeners->containsKey($eventName)) {
88
                return array();
89
            }
90
91
            return $this->listeners->get($eventName);
92
        }
93
94
        return $this->listeners;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->listeners; (Cubiche\Core\Collections\ArrayCollection) is incompatible with the return type declared by the interface Cubiche\Core\EventDispat...herInterface::listeners of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function listenerPriority($eventName, callable $listener)
101
    {
102
        if (!$this->listeners->containsKey($eventName)) {
103
            return;
104
        }
105
106
        /** @var SortedArrayCollection $sortedListeners */
107
        $sortedListeners = $this->listeners->get($eventName);
108
109
        /** @var ArrayCollection $listeners */
110
        foreach ($sortedListeners as $priority => $listeners) {
111
            foreach ($listeners as $registered) {
112
                /** @var DelegateListener $registered */
113
                if ($registered->equals($listener)) {
114
                    return $priority;
115
                }
116
            }
117
        }
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function hasListeners($eventName = null)
124
    {
125
        if ($eventName === null) {
126
            return $this->listeners->count() > 0;
127
        }
128
129
        return $this->listeners->containsKey($eventName);
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function addListener($eventName, callable $listener, $priority = 0)
136
    {
137
        if (!$this->listeners->containsKey($eventName)) {
138
            $this->listeners->set($eventName, new SortedArrayCollection([], new ReverseComparator(new Comparator())));
139
        }
140
141
        /** @var SortedArrayCollection $sortedListeners */
142
        $sortedListeners = $this->listeners->get($eventName);
143
        if (!$sortedListeners->containsKey($priority)) {
144
            $sortedListeners->set($priority, new ArrayCollection());
145
        }
146
147
        $sortedListeners->get($priority)->add(new DelegateListener($listener));
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function removeListener($eventName, callable $listener)
154
    {
155
        if (!$this->listeners->containsKey($eventName)) {
156
            return;
157
        }
158
159
        /** @var SortedArrayCollection $sortedListeners */
160
        $sortedListeners = $this->listeners->get($eventName);
161
162
        /** @var ArrayCollection $listeners */
163
        foreach ($sortedListeners as $priority => $listeners) {
164
            foreach ($listeners as $registered) {
165
                /** @var DelegateListener $registered */
166
                if ($registered->equals($listener)) {
167
                    $listeners->remove($registered);
168
                }
169
            }
170
171
            if ($listeners->count() == 0) {
172
                $sortedListeners->removeAt($priority);
173
            }
174
        }
175
176
        if ($sortedListeners->count() == 0) {
177
            $this->listeners->removeAt($eventName);
178
        }
179
    }
180
181
    /**
182
     * {@inheritdoc}
183
     */
184
    public function addSubscriber(EventSubscriberInterface $subscriber)
185
    {
186
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
187
            if (is_string($params)) {
188
                $this->addListener($eventName, array($subscriber, $params));
189
            } elseif (is_string($params[0])) {
190
                $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
191
            } else {
192
                foreach ($params as $listener) {
193
                    $this->addListener(
194
                        $eventName,
195
                        array($subscriber, $listener[0]),
196
                        isset($listener[1]) ? $listener[1] : 0
197
                    );
198
                }
199
            }
200
        }
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function removeSubscriber(EventSubscriberInterface $subscriber)
207
    {
208
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
209
            if (is_array($params) && is_array($params[0])) {
210
                foreach ($params as $listener) {
211
                    $this->removeListener($eventName, array($subscriber, $listener[0]));
212
                }
213
            } else {
214
                $this->removeListener($eventName, array($subscriber, is_string($params) ? $params : $params[0]));
215
            }
216
        }
217
    }
218
219
    /**
220
     * Triggers the listeners of an event.
221
     *
222
     * @param SortedArrayCollection $sortedListeners
223
     * @param EventInterface        $event
224
     */
225
    protected function doDispatch(SortedArrayCollection $sortedListeners, EventInterface $event)
226
    {
227
        foreach ($sortedListeners as $priority => $listeners) {
228
            foreach ($listeners as $listener) {
229
                $listener($event);
230
                /** @var EventInterface $event */
231
                if ($event->isPropagationStopped()) {
232
                    break;
233
                }
234
            }
235
        }
236
    }
237
}
238