Passed
Pull Request — master (#30)
by
unknown
15:04
created

DeferredProvider   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 9
eloc 20
c 1
b 0
f 1
dl 0
loc 52
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A clearEvents() 0 3 1
A dispatchEvent() 0 3 1
A deferEvents() 0 3 1
A dispatchEvents() 0 12 2
A getListenersForEvent() 0 6 2
A addEvent() 0 3 1
A __construct() 0 3 1
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
    public function getListenersForEvent(object $event): iterable
26
    {
27
        if ($this->deferEvents) {
28
            yield fn($event) => $this->addEvent($event);
29
        } else {
30
            yield fn($event) => $this->dispatchEvent($event);
31
        }
32
    }
33
34
    public function deferEvents(): void
35
    {
36
        $this->deferEvents = true;
37
    }
38
39
    public function clearEvents(): void
40
    {
41
        $this->events = [];
42
    }
43
44
    public function dispatchEvents(): array
45
    {
46
        $events = $this->events;
47
        $this->clearEvents();
48
        $this->deferEvents = false;
49
        $dispatchedEvents = [];
50
51
        foreach ($events as $event) {
52
            $dispatchedEvents[] = $this->dispatchEvent($event);
53
        }
54
55
        return $dispatchedEvents;
56
    }
57
58
    private function addEvent(object $event): void
59
    {
60
        $this->events[] = $event;
61
    }
62
63
    private function dispatchEvent(object $event): object
64
    {
65
        return $this->dispatcher->dispatch($event);
66
    }
67
}
68