Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
17 / 17 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| EventService | |
100.00% |
17 / 17 |
|
100.00% |
4 / 4 |
11 | |
100.00% |
1 / 1 |
| subscribeWithRef | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| subscribe | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| unsubscribe | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
5 | |||
| emit | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Dynart\Micro; |
| 4 | |
| 5 | class EventService { |
| 6 | |
| 7 | protected $subscriptions = []; |
| 8 | |
| 9 | public function subscribeWithRef(string $event, &$callable): void { |
| 10 | if (!array_key_exists($event, $this->subscriptions)) { |
| 11 | $this->subscriptions[$event] = []; |
| 12 | } |
| 13 | $this->subscriptions[$event][] = $callable; |
| 14 | } |
| 15 | |
| 16 | public function subscribe(string $event, $callable): void { |
| 17 | $this->subscribeWithRef($event, $callable); |
| 18 | } |
| 19 | |
| 20 | public function unsubscribe(string $event, &$callable): bool { |
| 21 | if (!array_key_exists($event, $this->subscriptions)) { |
| 22 | return false; |
| 23 | } |
| 24 | foreach ($this->subscriptions[$event] as $c) { |
| 25 | if ($c === $callable) { // TODO: not working on arrays with same values |
| 26 | $key = array_search($c, $this->subscriptions[$event]); |
| 27 | unset($this->subscriptions[$event][$key]); |
| 28 | if (empty($this->subscriptions[$event])) { |
| 29 | unset($this->subscriptions[$event]); |
| 30 | } |
| 31 | return true; |
| 32 | } |
| 33 | } |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | public function emit(string $event, array $args): void { |
| 38 | if (array_key_exists($event, $this->subscriptions)) { |
| 39 | foreach ($this->subscriptions[$event] as $callable) { |
| 40 | call_user_func_array(Micro::getCallable($callable), $args); |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | } |