-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathEventManager.php
More file actions
94 lines (75 loc) · 2.16 KB
/
Copy pathEventManager.php
File metadata and controls
94 lines (75 loc) · 2.16 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
<?php declare(strict_types = 1);
namespace Spameri\Elastic;
class EventManager
{
public const PRE_PERSIST = 'prePersist';
public const POST_PERSIST = 'postPersist';
public const POST_CREATE = 'postCreate';
public const POST_UPDATE = 'postUpdate';
public const PRE_DELETE = 'preDelete';
public const POST_DELETE = 'postDelete';
/**
* @var array<string, array<string, array<\Spameri\Elastic\EventManager\ListenerInterface>>>
*/
private array $listeners;
private bool $initialized = false;
public function __construct(
private readonly \Nette\DI\Container $container,
)
{
$this->listeners[self::PRE_PERSIST] = [];
$this->listeners[self::POST_PERSIST] = [];
$this->listeners[self::POST_CREATE] = [];
$this->listeners[self::POST_UPDATE] = [];
$this->listeners[self::PRE_DELETE] = [];
$this->listeners[self::POST_DELETE] = [];
}
public function addListener(
string $event,
string|null $entityClass,
\Spameri\Elastic\EventManager\ListenerInterface $listener,
): void
{
$this->listeners[$event][$entityClass][] = $listener;
}
private function initListeners(): void
{
if ($this->initialized === true) {
return;
}
$listeners = $this->container->findByType(\Spameri\Elastic\EventManager\ListenerInterface::class);
foreach ($listeners as $listenerName) {
/** @var \Spameri\Elastic\EventManager\ListenerInterface $listener */
$listener = $this->container->getService($listenerName);
foreach ($listener->getEntityClass() as $entityClass) {
$this->addListener(
event: $listener->getEvent(),
entityClass: $entityClass,
listener: $listener,
);
}
}
$this->initialized = true;
}
public function dispatch(
string $event,
string $entityClass,
object|null $entity = null,
object|null $parent = null,
): void
{
$this->initListeners();
foreach ($this->listeners[$event] as $listenerEntityClass => $listeners) {
if (
$listenerEntityClass !== ''
&& \is_a($entityClass, $listenerEntityClass, true) === false
) {
continue;
}
/** @var \Spameri\Elastic\EventManager\ListenerInterface $listener */
foreach ($listeners as $listener) {
$listener->handle($entity, $parent);
}
}
}
}