EventForwarder   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 82
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A forwardEvent() 0 8 2
A forwardAllEvents() 0 19 4
1
<?php
2
3
namespace Eole\Sandstone\Push;
4
5
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
6
use Symfony\Component\EventDispatcher\Event;
7
use Eole\Sandstone\Push\PushServerInterface;
8
9
class EventForwarder
10
{
11
    /**
12
     * @var PushServerInterface
13
     */
14
    private $pushServer;
15
16
    /**
17
     * @var EventDispatcherInterface
18
     */
19
    private $dispatcher;
20
21
    /**
22
     * @var EventSerializer
23
     */
24
    private $eventSerializer;
25
26
    /**
27
     * @var bool
28
     */
29
    private $enabled;
30
31
    /**
32
     * @param PushServerInterface $pushServer
33
     * @param EventDispatcherInterface $dispatcher
34
     * @param EventSerializer $eventSerializer
35
     * @param bool $enabled
36
     */
37
    public function __construct(
38
        PushServerInterface $pushServer,
39
        EventDispatcherInterface $dispatcher,
40
        EventSerializer $eventSerializer,
41
        $enabled = true
42
    ) {
43
        $this->pushServer = $pushServer;
44
        $this->dispatcher = $dispatcher;
45
        $this->eventSerializer = $eventSerializer;
46
        $this->enabled = $enabled;
47
    }
48
49
    /**
50
     * Forward an Event to Push Server.
51
     *
52
     * @param Event $event
53
     * @param string $name
54
     */
55
    public function forwardEvent(Event $event, $name)
56
    {
57
        if (!$this->enabled) {
58
            return;
59
        }
60
61
        $this->pushServer->send($this->eventSerializer->serializeEvent($name, $event));
62
    }
63
64
    /**
65
     * Automatically forward RestApi events to push server.
66
     *
67
     * @param string|string[] $eventNames Can be an event name or an array of event names.
68
     *
69
     * @return self
70
     */
71
    public function forwardAllEvents($eventNames)
72
    {
73
        if (!$this->enabled) {
74
            return $this;
75
        }
76
77
        if (!is_array($eventNames)) {
78
            $eventNames = array($eventNames);
79
        }
80
81
        foreach ($eventNames as $eventName) {
82
            $this->dispatcher->addListener(
83
                $eventName,
84
                array($this, 'forwardEvent')
85
            );
86
        }
87
88
        return $this;
89
    }
90
}
91