Completed
Pull Request — master (#1742)
by Gabriel
229:44 queued 164:40
created

EventDispatcher::dispatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
rs 10
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\Fundraising\Frontend\Infrastructure\EventHandling;
6
7
use WMDE\Fundraising\DonationContext\Domain\Event as DonationEvent;
8
use WMDE\Fundraising\MembershipContext\Domain\Event as MembershipEvent;
9
10
class EventDispatcher {
11
12
	/**
13
	 * @var callable[][]
14
	 */
15
	protected array $listeners = [];
16
17
	public function addEventListener( string $eventClassName, callable $listener ): self {
18
		assert( class_exists( $eventClassName ) );
19
		if ( empty( $this->listeners[$eventClassName] ) ) {
20
			$this->listeners[$eventClassName] = [];
21
		}
22
		$this->listeners[$eventClassName][] = $listener;
23
		return $this;
24
	}
25
26
	/**
27
	 * @param DonationEvent|MembershipEvent $event
28
	 */
29
	public function dispatch( $event ): void {
30
		$eventName = get_class( $event );
31
		if ( empty( $this->listeners[$eventName] ) ) {
32
			return;
33
		}
34
		array_map( fn( $handler ) => \call_user_func( $handler, $event ), $this->listeners[$eventName] );
35
	}
36
}
37