1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\EventDispatcher\Provider; |
6
|
|
|
|
7
|
|
|
use Psr\EventDispatcher\EventDispatcherInterface; |
8
|
|
|
use Psr\EventDispatcher\ListenerProviderInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* DeferredProvider is a listener provider that allows you to perform deferred |
12
|
|
|
* events |
13
|
|
|
*/ |
14
|
|
|
final class DeferredProvider implements ListenerProviderInterface |
15
|
|
|
{ |
16
|
|
|
private EventDispatcherInterface $dispatcher; |
17
|
|
|
private bool $deferEvents = false; |
18
|
|
|
private array $events = []; |
19
|
|
|
|
20
|
|
|
public function __construct(EventDispatcherInterface $dispatcher) |
21
|
|
|
{ |
22
|
|
|
$this->dispatcher = $dispatcher; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* returns a relevant listener or defer event |
27
|
|
|
*/ |
28
|
|
|
public function getListenersForEvent(object $event): iterable |
29
|
|
|
{ |
30
|
|
|
if ($this->deferEvents) { |
31
|
|
|
yield fn ($event) => $this->addEvent($event); |
32
|
|
|
} else { |
33
|
|
|
yield fn ($event) => $this->dispatchEvent($event); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Enable deferred event mode |
39
|
|
|
*/ |
40
|
|
|
public function deferEvents(): void |
41
|
|
|
{ |
42
|
|
|
$this->deferEvents = true; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Deletes all deferred events |
47
|
|
|
*/ |
48
|
|
|
public function clearEvents(): void |
49
|
|
|
{ |
50
|
|
|
$this->events = []; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Dispatch all deferred events |
55
|
|
|
* |
56
|
|
|
* @return array dispatch events |
57
|
|
|
*/ |
58
|
|
|
public function dispatchEvents(): array |
59
|
|
|
{ |
60
|
|
|
$events = $this->events; |
61
|
|
|
$this->clearEvents(); |
62
|
|
|
$this->deferEvents = false; |
63
|
|
|
$dispatchedEvents = []; |
64
|
|
|
|
65
|
|
|
foreach ($events as $event) { |
66
|
|
|
$dispatchedEvents[] = $this->dispatchEvent($event); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $dispatchedEvents; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function addEvent(object $event): void |
73
|
|
|
{ |
74
|
|
|
$this->events[] = $event; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
private function dispatchEvent(object $event): object |
78
|
|
|
{ |
79
|
|
|
return $this->dispatcher->dispatch($event); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|