Mediator::notify()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Wonderland\Thread\Mediator;
4
5
use Wonderland\Thread\Mediator\Event\EventInterface;
6
use Wonderland\Thread\Mediator\Listener\ListenerInterface;
7
8
class Mediator
9
{
10
	/** @var ListenerInterface[][] */
11
	private $listeners = [];
12
13
	/**
14
	 * @return ListenerInterface[][]
15
	 */
16 1
	public function getListeners(): array
17
	{
18 1
		return $this->listeners;
19
	}
20
21
	/**
22
	 * @param ListenerInterface $listener
23
	 * @return Mediator
24
	 */
25 2
	public function addListener(ListenerInterface $listener): self
26
	{
27 2
		$this->listeners[$listener->getEventName()][] = $listener;
28
29 2
		return $this;
30
	}
31
32
	/**
33
	 * @param ListenerInterface $listener
34
	 * @return Mediator
35
	 */
36 2
	public function removeListener(ListenerInterface $listener): self
37
	{
38 2
		if (!isset($this->listeners[$listener->getEventName()])) {
39 1
			return $this;
40
		}
41
42 2
		$key = array_search($listener, $this->listeners[$listener->getEventName()]);
43
44 2
		if (false !== $key) {
45 2
			unset($this->listeners[$listener->getEventName()][$key]);
46
		}
47
48 2
		if (empty($this->listeners[$listener->getEventName()])) {
49 2
			unset($this->listeners[$listener->getEventName()]);
50
		}
51
52 2
		return $this;
53
	}
54
55
	/**
56
	 * @param string $eventName
57
	 * @param EventInterface $event
58
	 */
59 2
	public function notify($eventName, EventInterface $event)
60
	{
61 2
		if (!isset($this->listeners[$eventName])) {
62 1
			return;
63
		}
64
65 2
		foreach ($this->listeners[$eventName] as $listener) {
66 2
			$listener->notify($event);
67
		}
68 2
	}
69
70
}
71