Completed
Push — master ( 25ba26...942c9a )
by dan
02:00
created

EventChannel::format()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 1
1
<?php
2
3
namespace IrishDan\NotificationBundle\Channel;
4
5
use IrishDan\NotificationBundle\Dispatcher\MessageDispatcherInterface;
6
use IrishDan\NotificationBundle\Event\MessageCreatedEvent;
7
use IrishDan\NotificationBundle\Event\MessageDispatchedEvent;
8
use IrishDan\NotificationBundle\Exception\MessageDispatchException;
9
use IrishDan\NotificationBundle\Message\MessageInterface;
10
use IrishDan\NotificationBundle\Notification\NotificationInterface;
11
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
12
13
/**
14
 * Class DefaultChannel
15
 *
16
 * @package NotificationBundle\Channel
17
 */
18
class EventChannel extends BaseChannel implements ChannelInterface
19
{
20
    private $dispatchers = [];
21
    private $eventDispatcher;
22
23
    public function formatAndDispatch(NotificationInterface $notification)
24
    {
25
        $this->format($notification);
0 ignored issues
show
Bug introduced by
The method format() does not exist on IrishDan\NotificationBundle\Channel\EventChannel. Did you maybe mean formatAndDispatch()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
26
    }
27
28
    public function setDispatchers($key, MessageDispatcherInterface $dispatcher)
29
    {
30
        $this->dispatchers[$key] = $dispatcher;
31
    }
32
33
    public function __construct(EventDispatcherInterface $eventDispatcher)
34
    {
35
        $this->eventDispatcher = $eventDispatcher;
36
    }
37
38
    public function dispatchFromEvent(MessageCreatedEvent $event)
39
    {
40
        $message = $event->getMessage();
41
        $this->dispatch($message);
42
    }
43
44
    public function dispatch(MessageInterface $message)
45
    {
46
        $dispatcherKey = $message->getChannel();
47
48
        // Dispatch the message
49
        try {
50
            if (!empty($this->dispatchers[$dispatcherKey])) {
51
                $this->dispatchers[$dispatcherKey]->dispatch($message);
52
            } else {
53
                throw new MessageDispatchException(
54
                    sprintf('No dispatcher available with key "%s"', $dispatcherKey)
55
                );
56
            }
57
        } catch (\Exception $exception) {
58
            throw new MessageDispatchException($exception->getMessage());
59
        }
60
61
        // Dispatch the message event
62
        $messageEvent = new MessageDispatchedEvent($message);
63
        $this->eventDispatcher->dispatch(MessageDispatchedEvent::NAME, $messageEvent);
64
    }
65
}
66