-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventListenerProvider.php
More file actions
103 lines (88 loc) · 2.76 KB
/
EventListenerProvider.php
File metadata and controls
103 lines (88 loc) · 2.76 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* This file is part of the Vection package.
*
* (c) David M. Lung <vection@davidlung.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Vection\Component\Event;
use Vection\Contracts\Event\EventListenerFactoryInterface;
use Vection\Contracts\Event\EventListenerProviderInterface;
/**
* Class EventListenerProvider
*
* @package Vection\Component\Event
*
* @author David Lung <vection@davidlung.de>
*/
class EventListenerProvider implements EventListenerProviderInterface
{
/** @var mixed[] */
protected array $listeners = [];
protected EventListenerFactoryInterface|null $eventListenerFactory;
/**
* @var callable|null
*/
protected $lazyListenerLoader = null;
/**
* EventListenerProvider constructor.
*
* @param EventListenerFactoryInterface|null $eventListenerFactory
*/
public function __construct(?EventListenerFactoryInterface $eventListenerFactory = null)
{
$this->eventListenerFactory = $eventListenerFactory;
}
/**
* Loads and registers all listeners just before the first listener
* is requested by the event dispatcher.
*
* @param callable $fn
*/
public function onLazyLoad(callable $fn): void
{
$this->lazyListenerLoader = $fn;
}
/**
* @param string $event
* @param string $listener
* @param string $method
*/
public function register(string $event, string $listener, string $method = '__invoke'): void
{
if (! isset($this->listeners[$event])) {
$this->listeners[$event] = [];
}
$this->listeners[$event][] = [
'class' => $listener,
'method' => $method
];
}
/**
* @param object $event An event for which to return the relevant listeners.
*
* @return mixed[] An iterable (array, iterator, or generator) of callables. Each callable MUST be type-compatible
* with $event.
*/
public function getListenersForEvent(object $event): iterable
{
$listeners = [];
if ($this->lazyListenerLoader !== null && count($this->listeners) === 0) {
($this->lazyListenerLoader)($this);
}
if (isset($this->listeners[get_class($event)])) {
foreach ($this->listeners[get_class($event)] as $listener) {
if ($this->eventListenerFactory !== null) {
$object = $this->eventListenerFactory->create($listener['class']);
} else {
$object = new $listener['class'];
}
$listeners[] = [$object, $listener['method']];
}
}
return $listeners;
}
}