forked from SonsOfPHP/sonsofphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventDispatcher.php
More file actions
58 lines (47 loc) · 1.51 KB
/
EventDispatcher.php
File metadata and controls
58 lines (47 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\EventDispatcher;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\EventDispatcher\StoppableEventInterface;
/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class EventDispatcher implements EventDispatcherInterface
{
public function __construct(
private readonly ListenerProviderInterface $provider = new ListenerProvider(),
) {}
/**
* {@inheritdoc}
*
* @param string|null $eventName
* Is the event name is null, is will use the event's classname as the Event Name
*/
public function dispatch(object $event, ?string $eventName = null): object
{
$eventName ??= $event::class;
foreach ($this->provider->getListenersForEventName($eventName) as $listener) {
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
return $event;
}
$listener($event, $eventName, $this);
}
return $event;
}
/**
*/
public function addListener(string|object $eventName, callable|array $listener, int $priority = 0): void
{
if (is_object($eventName)) {
$eventName = $eventName::class;
}
$this->provider->add($eventName, $listener, $priority);
}
/**
*/
public function addSubscriber(EventSubscriberInterface $subscriber): void
{
$this->provider->addSubscriber($subscriber);
}
}