Completed
Push — master ( 44f310...207ea5 )
by Torsten
03:42
created

DomainEventPublisher::__clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lej\Component\Domain\Model;
6
7
class DomainEventPublisher
8
{
9
    /**
10
     * @var DomainEventPublisher
11
     */
12
    private static $instance;
13
14
    /**
15
     * @var DomainEventSubscriber[][]
16
     */
17
    private $subscribers;
18
19
    /**
20
     * Returns an instance of the publisher.
21
     * @return DomainEventPublisher
22
     */
23 3
    public static function instance() : DomainEventPublisher
24
    {
25 3
        return self::$instance ? self::$instance : new self();
26
    }
27
28
    /**
29
     * Publishes a domain event by notifying all the subscribers subscribed to
30
     * this event type. Subscribers can be notified for all events if they
31
     * subscribe to DomainEvent::class.
32
     * @param DomainEvent $event
33
     */
34 3
    public function publish(DomainEvent $event)
35
    {
36 3
        $subscribers = [];
37 3
        $eventType = get_class($event);
38
39 3
        if (isset($this->subscribers[$eventType])) {
40 1
            $subscribers += $this->subscribers[$eventType];
41
        }
42
43 3
        if (isset($this->subscribers[DomainEvent::class])) {
44 1
            $subscribers += $this->subscribers[DomainEvent::class];
45
        }
46
47 3
        foreach ($subscribers as $subscriber) {
48 2
            $subscriber->handleEvent($event);
49
        }
50 3
    }
51
52
    /**
53
     * Resets the publisher by removing all the current subscribers.
54
     */
55 1
    public function reset()
56
    {
57 1
        $this->subscribers = [];
58 1
    }
59
60
    /**
61
     * @param DomainEventSubscriber $subscriber
62
     */
63 3
    public function subscribe(DomainEventSubscriber $subscriber)
64
    {
65 3
        $this->subscribers[$subscriber->subscribedToEventType()][] = $subscriber;
66 3
    }
67
68
    /**
69
     * The constructor.
70
     */
71 3
    private function __construct()
72
    {
73 3
        $this->subscribers = [];
74 3
    }
75
76
    /**
77
     * Clones the publisher.
78
     */
79
    private function __clone()
80
    {
81
    }
82
}
83