-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventSubscribersCollection.php
More file actions
78 lines (67 loc) · 2.8 KB
/
Copy pathEventSubscribersCollection.php
File metadata and controls
78 lines (67 loc) · 2.8 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
<?php
declare(strict_types=1);
namespace WonderNetwork\SlimKernel\EventDispatcher;
use Psr\Container\ContainerInterface;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WonderNetwork\SlimKernel\ServiceFactory;
use WonderNetwork\SlimKernel\ServicesBuilder;
use function DI\decorate;
final readonly class EventSubscribersCollection implements ServiceFactory {
public static function start(): self {
return new self([]);
}
/**
* @param list<class-string<EventSubscriberInterface>> $subscribers
*/
public function __construct(private array $subscribers) {
}
public function __invoke(ServicesBuilder $builder): iterable {
yield from $this->register();
}
/**
* @param class-string<EventSubscriberInterface> ...$subscribers
*/
public function add(string ...$subscribers): self {
return new self([...$this->subscribers, ...array_values($subscribers)]);
}
public function addLazyListeners(EventDispatcher $dispatcher, ContainerInterface $container): EventDispatcher {
foreach ($this->subscribers as $subscriber) {
$factory = LazyListenerFactory::of($container, $subscriber);
/**
* @see EventDispatcher::addSubscriber()
*/
foreach ($subscriber::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$dispatcher->addListener($eventName, $factory->create($params));
} elseif (\is_string($params[0])) {
$dispatcher->addListener($eventName, $factory->create($params[0]), (int) ($params[1] ?? 0));
} else {
foreach ($params as $listener) {
if (is_string($listener)) {
$dispatcher->addListener($eventName, $factory->create($listener));
} elseif (is_array($listener)) {
$priority = (int) ($listener[1] ?? 0);
$dispatcher->addListener($eventName, $factory->create($listener[0]), $priority);
} else {
throw new RuntimeException('Invalid event listener: '.$subscriber);
}
}
}
}
}
return $dispatcher;
}
/**
* @return iterable<string,mixed>
*/
public function register(): iterable {
yield self::class => $this;
yield EventDispatcher::class => decorate(
fn (EventDispatcher $dispatcher, ContainerInterface $container) => $container
->get(EventSubscribersCollection::class)
->addLazyListeners($dispatcher, $container),
);
}
}