EventDispatcherTrait::dispatch()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
ccs 4
cts 4
cp 1
cc 1
nc 1
nop 2
crap 1
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 86
    protected function getEventDispatcher()
29
    {
30 86
        if (is_null($this->eventDispatcher)) {
31 86
            $this->eventDispatcher = new EventDispatcher();
32 86
        }
33 86
        return $this->eventDispatcher;
34
    }
35
36
    /**
37
     * @return string[]
38
     */
39
    abstract protected function getEventNames();
40
41
    /**
42
     * @param string   $name
43
     * @param callable $handler
44
     *
45
     * @return $this
46
     */
47 78
    public function addListener($name, callable $handler)
48
    {
49 78
        $this->assertEventName($name);
50 77
        $this->getEventDispatcher()->addListener($name, $handler);
51 77
        return $this;
52
    }
53
54
    /**
55
     * @param string $name
56
     * @param Event  $event
57
     *
58
     * @return $this
59
     */
60 80
    protected function dispatch($name, Event $event)
61
    {
62 80
        $this->assertEventName($name);
63 79
        $this->getEventDispatcher()->dispatch($name, $event);
64 79
        return $this;
65 1
    }
66
67
    /**
68
     * @param string $name
69
     *
70
     * @throws \InvalidArgumentException
71
     */
72 88
    private function assertEventName($name)
73
    {
74 88
        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 2
            ));
80
        }
81 86
    }
82
}
83