Passed
Pull Request — master (#14)
by Alex
02:34
created

AbstractEventDispatcher   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 6
eloc 10
c 1
b 1
f 0
dl 0
loc 43
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isPropagationStopped() 0 3 2
A dispatch() 0 15 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\EventDispatcher;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Psr\EventDispatcher\ListenerProviderInterface;
9
use Psr\EventDispatcher\StoppableEventInterface;
10
11
/**
12
 * @author  Alex Patterson <[email protected]>
13
 * @package Arp\EventDispatcher
14
 */
15
abstract class AbstractEventDispatcher implements EventDispatcherInterface
16
{
17
    /**
18
     * @var ListenerProviderInterface
19
     */
20
    protected $listenerProvider;
21
22
    /**
23
     * Trigger the registered collection of events.
24
     *
25
     * @param object $event The event that should be triggered.
26
     *
27
     * @return object
28
     *
29
     * @throws \Throwable If an event listener throws an exception
30
     */
31
    public function dispatch(object $event): object
32
    {
33
        if ($this->isPropagationStopped($event)) {
34
            return $event;
35
        }
36
37
        foreach ($this->listenerProvider->getListenersForEvent($event) as $listener) {
38
            $listener($event);
39
40
            if ($this->isPropagationStopped($event)) {
41
                break;
42
            }
43
        }
44
45
        return $event;
46
    }
47
48
    /**
49
     * Check if the event propagation has been stopped.
50
     *
51
     * @param object $event
52
     *
53
     * @return bool
54
     */
55
    protected function isPropagationStopped(object $event): bool
56
    {
57
        return ($event instanceof StoppableEventInterface && $event->isPropagationStopped());
58
    }
59
}
60