|
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
|
|
|
|