1 | <?php |
||
18 | class CallbackEventHandler implements \Countable, EventHandlerInterface |
||
19 | { |
||
20 | /** |
||
21 | * List of callables in this bag indexed by event name |
||
22 | * |
||
23 | * @var array |
||
24 | */ |
||
25 | private $handlers = []; |
||
26 | |||
27 | /** |
||
28 | * CallbackEventHandler constructor. |
||
29 | * |
||
30 | * @param array $events Events to handle: [ "eventName" => callable|callable[], ... ] |
||
31 | */ |
||
32 | 133 | public function __construct(array $events = []) |
|
33 | { |
||
34 | 133 | $this->addHandler($events); |
|
35 | 133 | } |
|
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 | 133 | public function addHandler(array $events) |
|
46 | { |
||
47 | 133 | foreach ($events as $eventName => $subscriber) { |
|
48 | 130 | $this->handlers[$eventName] = array_merge( |
|
49 | 130 | isset($this->handlers[$eventName]) ? $this->handlers[$eventName] : [], |
|
50 | 130 | is_callable($subscriber) ? [$subscriber] : $subscriber |
|
51 | 130 | ); |
|
52 | 133 | } |
|
53 | 133 | } |
|
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) |
|
102 | |||
103 | /** {@inheritdoc} */ |
||
104 | 130 | public function invokeEvent( |
|
116 | |||
117 | /** {@inheritdoc} */ |
||
118 | 1 | public function count() |
|
122 | } |
||
123 |