1 | <?php |
||
17 | class CallbackEventHandler implements \Countable, EventHandlerInterface |
||
18 | { |
||
19 | /** |
||
20 | * List of callables in this bag indexed by event name |
||
21 | * |
||
22 | * @var array |
||
23 | */ |
||
24 | private $handlers = []; |
||
25 | |||
26 | /** |
||
27 | * CallbackEventHandler constructor. |
||
28 | * |
||
29 | * @param array $events Events to handle: [ "eventName" => callable|callable[], ... ] |
||
30 | */ |
||
31 | 123 | public function __construct(array $events = []) |
|
32 | { |
||
33 | 123 | $this->handlers = []; |
|
34 | 123 | $this->addHandler($events); |
|
35 | 123 | } |
|
36 | |||
37 | |||
38 | /** |
||
39 | * Add handler into this bag |
||
40 | * |
||
41 | * @param array $events Events to handle: [ "eventName" => callable|callable[], ... ] |
||
42 | * |
||
43 | * @return void |
||
44 | */ |
||
45 | 123 | public function addHandler(array $events) |
|
54 | |||
55 | /** |
||
56 | * Remove specified handlers from this bag |
||
57 | * |
||
58 | * @param array $events Events to remove: [ "eventName" => callable|callable[], ... ] |
||
59 | * |
||
60 | * @return void |
||
61 | */ |
||
62 | 4 | public function removeHandler(array $events) |
|
63 | { |
||
64 | 4 | foreach ($events as $eventName => $subscribers) { |
|
65 | 4 | if (!isset($this->handlers[$eventName])) { |
|
66 | 2 | continue; |
|
67 | } |
||
68 | |||
69 | 2 | $subscribers = is_callable($subscribers) ? [$subscribers] : $subscribers; |
|
70 | 2 | foreach ($subscribers as $subscriber) { |
|
71 | 2 | $key = array_search($subscriber, $this->handlers[$eventName], true); |
|
72 | 2 | if ($key !== false) { |
|
73 | 2 | unset($this->handlers[$eventName][$key]); |
|
74 | 2 | } |
|
75 | 2 | } |
|
76 | 4 | } |
|
77 | 4 | } |
|
78 | |||
79 | /** |
||
80 | * Remove all handlers from bag |
||
81 | * |
||
82 | * @return void |
||
83 | */ |
||
84 | 2 | public function removeAll() |
|
88 | |||
89 | /** |
||
90 | * Remove all handlers for given event name |
||
91 | * |
||
92 | * @param string $eventName Event name to remove handlers |
||
93 | * |
||
94 | * @return void |
||
95 | */ |
||
96 | 2 | public function removeForEvent($eventName) |
|
97 | { |
||
98 | 2 | if (isset($this->handlers[$eventName])) { |
|
99 | 2 | unset($this->handlers[$eventName]); |
|
100 | 2 | } |
|
101 | 2 | } |
|
102 | |||
103 | /** {@inheritdoc} */ |
||
104 | 120 | public function invokeEvent(Event $event) |
|
105 | { |
||
106 | 120 | $eventName = $event->getType(); |
|
107 | 120 | $subscribers = isset($this->handlers[$eventName]) ? $this->handlers[$eventName] : []; |
|
108 | 120 | foreach ($subscribers as $subscriber) { |
|
109 | 118 | call_user_func($subscriber, $event); |
|
110 | 112 | } |
|
111 | 112 | } |
|
112 | |||
113 | /** {@inheritdoc} */ |
||
114 | 1 | public function count() |
|
118 | } |
||
119 |