Passed
Pull Request — master (#16)
by Harry
07:40 queued 02:51
created

EventDispatcherTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 16
dl 0
loc 59
rs 10
c 0
b 0
f 0
ccs 18
cts 18
cp 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getEventDispatcher() 0 6 2
A dispatch() 0 5 1
A addListener() 0 5 1
A assertEventName() 0 7 2
1
<?php
2
/**
3
 * This file is part of graze/parallel-process.
4
 *
5
 * Copyright © 2018 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/parallel-process/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/parallel-process
12
 */
13
14
namespace Graze\ParallelProcess\Event;
15
16
use Symfony\Component\EventDispatcher\Event;
17
use Symfony\Component\EventDispatcher\EventDispatcher;
18
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
19
20
trait EventDispatcherTrait
21
{
22
    /** @var EventDispatcherInterface */
23
    protected $eventDispatcher;
24
25
    /**
26
     * @return EventDispatcherInterface
27
     */
28 61
    protected function getEventDispatcher()
29
    {
30 61
        if (is_null($this->eventDispatcher)) {
31 61
            $this->eventDispatcher = new EventDispatcher();
32
        }
33 61
        return $this->eventDispatcher;
34
    }
35
36
    /**
37
     * @return string[]
38
     */
39
    protected abstract function getEventNames();
40
41
    /**
42
     * @param string   $eventName
43
     * @param callable $handler
44
     *
45
     * @return $this
46
     */
47 49
    public function addListener($eventName, callable $handler)
48
    {
49 49
        $this->assertEventName($eventName);
50 48
        $this->getEventDispatcher()->addListener($eventName, $handler);
51 48
        return $this;
52
    }
53
54
    /**
55
     * @param string $eventName
56
     * @param Event  $event
57
     *
58
     * @return $this
59
     */
60 55
    protected function dispatch($eventName, Event $event)
61
    {
62 55
        $this->assertEventName($eventName);
63 54
        $this->getEventDispatcher()->dispatch($eventName, $event);
64 54
        return $this;
65
    }
66
67
    /**
68
     * @param string $name
69
     *
70
     * @throws \InvalidArgumentException
71
     */
72 63
    private function assertEventName($name)
73
    {
74 63
        if (!in_array($name, $this->getEventNames())) {
75 2
            throw new \InvalidArgumentException(sprintf(
76 2
                'The supplied event name: %s is not one of the expected: %s',
77 2
                $name,
78 2
                implode(', ', $this->getEventNames())
79
            ));
80
        }
81 61
    }
82
}
83