Completed
Push — master ( 9f8fa7...d4ecd2 )
by Ivannis Suárez
06:56
created

EventDispatcher::dispatch()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 26
rs 8.5806
cc 4
eloc 14
nc 8
nop 1
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\ArrayHashMap;
14
use Cubiche\Core\Collections\ArrayCollection\ArrayList;
15
use Cubiche\Core\Collections\ArrayCollection\SortedArrayHashMap;
16
use Cubiche\Core\Comparable\Comparator;
17
use Cubiche\Core\Comparable\ReverseComparator;
18
19
/**
20
 * EventDispatcher class.
21
 *
22
 * @author Ivannis Suárez Jerez <[email protected]>
23
 */
24
class EventDispatcher implements EventDispatcherInterface
25
{
26
    /**
27
     * @var ArrayHashMap
28
     */
29
    protected $listeners;
30
31
    /**
32
     * EventDispatcher constructor.
33
     */
34
    public function __construct()
35
    {
36
        $this->listeners = new ArrayHashMap();
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function dispatch($event)
43
    {
44
        $event = $this->ensureEvent($event);
45
46
        // pre dispatch event
47
        $preDispatchEvent = new PreDispatchEvent($event);
48
        $eventName = $preDispatchEvent->eventName();
49
        if ($listeners = $this->eventListeners($eventName)) {
50
            $this->doDispatch($listeners, $preDispatchEvent);
51
        }
52
53
        // dispatch event
54
        $eventName = $event->eventName();
55
        if ($listeners = $this->eventListeners($eventName)) {
56
            $this->doDispatch($listeners, $event);
57
        }
58
59
        // post dispatch event
60
        $postDispatchEvent = new PostDispatchEvent($event);
61
        $eventName = $postDispatchEvent->eventName();
62
        if ($listeners = $this->eventListeners($eventName)) {
63
            $this->doDispatch($listeners, $postDispatchEvent);
64
        }
65
66
        return $event;
67
    }
68
69
    /**
70
     * Ensure event input is of type EventInterface or convert it.
71
     *
72
     * @param string|EventInterface $event
73
     *
74
     * @throws InvalidArgumentException
75
     *
76
     * @return EventInterface
77
     */
78
    public function ensureEvent($event)
79
    {
80
        if (is_string($event)) {
81
            return Event::named($event);
82
        }
83
84
        if (!$event instanceof EventInterface) {
85
            throw new \InvalidArgumentException(
86
                sprintf(
87
                    'Events should be provides as %s instances or string, received type: %s',
88
                    EventInterface::class,
89
                    gettype($event)
90
                )
91
            );
92
        }
93
94
        return $event;
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function eventListeners($eventName)
101
    {
102
        if (!$this->listeners->containsKey($eventName)) {
103
            return array();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(); (array) is incompatible with the return type declared by the interface Cubiche\Core\EventDispat...terface::eventListeners of type Cubiche\Core\Collections...tion\SortedArrayHashMap.

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