1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Moss micro-framework |
5
|
|
|
* |
6
|
|
|
* (c) Michal Wachowski <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Moss\Storage\Query\EventDispatcher; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Event dispatcher |
16
|
|
|
* |
17
|
|
|
* @author Michal Wachowski <[email protected]> |
18
|
|
|
* @package Moss\Storage |
19
|
|
|
*/ |
20
|
|
|
final class EventDispatcher implements EventDispatcherInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
private $events = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Adds listener to single event or array of events |
29
|
|
|
* |
30
|
|
|
* @param string|array $event |
31
|
|
|
* @param callable $listener |
32
|
|
|
* @param null|int $priority |
33
|
|
|
* |
34
|
|
|
* @return $this |
35
|
|
|
*/ |
36
|
|
|
public function register($event, callable $listener, $priority = null) |
37
|
|
|
{ |
38
|
|
|
foreach ((array) $event as $e) { |
39
|
|
|
$this->registerListener($e, $listener, $priority); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Register listener to event |
47
|
|
|
* |
48
|
|
|
* @param string $event |
49
|
|
|
* @param callable $listener |
50
|
|
|
* @param int $priority |
51
|
|
|
*/ |
52
|
|
|
private function registerListener($event, callable $listener, $priority) |
53
|
|
|
{ |
54
|
|
|
if (!isset($this->events[$event])) { |
55
|
|
|
$this->events[$event] = []; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if ($priority === null) { |
59
|
|
|
$this->events[$event][] = $listener; |
60
|
|
|
|
61
|
|
|
return; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
array_splice($this->events[$event], (int) $priority, 0, [$listener]); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Fires event |
69
|
|
|
* |
70
|
|
|
* @param string $eventName |
71
|
|
|
* @param mixed $subject |
72
|
|
|
* |
73
|
|
|
* @return mixed |
74
|
|
|
* @throws \Exception |
75
|
|
|
*/ |
76
|
|
|
public function fire($eventName, $subject = null) |
77
|
|
|
{ |
78
|
|
|
if (!isset($this->events[$eventName])) { |
79
|
|
|
return $subject; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$event = new Event($eventName, $subject); |
83
|
|
|
|
84
|
|
|
foreach ($this->events[$eventName] as $listener) { |
85
|
|
|
if ($event->isStopped()) { |
86
|
|
|
break; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
$listener($event); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return $event->getSubject(); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|