Completed
Push — refactor-quim ( 7ccf46...14758d )
by Quim
03:52
created

Subscriber::getSubscriptors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace Domain\Event;
3
4
use Domain\Event\Exception\DomainEventException;
5
use Domain\Queue\QueueReader;
6
use Psr\Log\LoggerInterface;
7
8
class Subscriber
9
{
10
    /**
11
     * @var QueueReader
12
     */
13
    protected $queueReader;
14
15
    /**
16
     * @var LoggerInterface
17
     */
18
    protected $logger;
19
20
    /**
21
     * @var EventSubscriptor[]
22
     */
23
    protected $subscriptors = [];
24
25
    /**
26
     * Subscriber constructor.
27
     * @param QueueReader $queueReader
28
     */
29
    public function __construct(QueueReader $queueReader, LoggerInterface $logger)
30
    {
31
        $this->queueReader = $queueReader;
32
        $this->logger = $logger;
33
    }
34
35
    /**
36
     * @param EventSubscriptor $eventSubscriptor
37
     * @return $this
38
     */
39
    public function subscribe(EventSubscriptor $eventSubscriptor)
40
    {
41
        $this->subscriptors[] = $eventSubscriptor;
42
        return $this;
43
    }
44
45
    public function start($timeout=0)
46
    {
47
        if(!isset($this->subscriptors[0])) {
48
            throw new DomainEventException('You must add at least 1 EventSubscriptor in order to publish start reading from queue.');
49
        }
50
        while(true) {
51
            try {
52
                $this->queueReader->read(array($this, 'notify'), $timeout);
53
            } catch(\Exception $e) {
54
                break;
55
            }
56
        }
57
    }
58
59
    /**
60
     * @param DomainEvent $domainEvent
61
     */
62
    public function notify(DomainEvent $domainEvent)
63
    {
64
        $this->logger->info('Domain Event received, notifying subscribers');
65
        foreach($this->subscriptors as $subscriptor) {
66
            if($subscriptor->isSubscribed($domainEvent)) {
67
                $subscriptor->notify($domainEvent);
68
            }
69
        }
70
    }
71
72
    /**
73
     * @return EventSubscriptor[]
74
     */
75
    public function getSubscriptors()
76
    {
77
        return $this->subscriptors;
78
    }
79
}