1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NilPortugues\MessageBus\EventBus\Translator; |
4
|
|
|
|
5
|
|
|
use NilPortugues\MessageBus\EventBus\Contracts\Event; |
6
|
|
|
use NilPortugues\MessageBus\EventBus\Contracts\EventHandler; |
7
|
|
|
use NilPortugues\MessageBus\EventBus\Contracts\EventHandlerPriority; |
8
|
|
|
use NilPortugues\MessageBus\EventBus\Contracts\EventTranslator; |
9
|
|
|
use RuntimeException; |
10
|
|
|
|
11
|
|
|
class EventFullyQualifiedClassNameStrategy implements EventTranslator |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var array |
15
|
|
|
*/ |
16
|
|
|
protected $listeners = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* An array of strings representing the FQN of the Event Handler. |
20
|
|
|
* |
21
|
|
|
* @param string[] $handlers |
22
|
|
|
*/ |
23
|
|
|
public function __construct(array $handlers) |
24
|
|
|
{ |
25
|
|
|
foreach ($handlers as $handler) { |
26
|
|
|
if (false === class_exists($handler, true)) { |
27
|
|
|
throw new RuntimeException( |
28
|
|
|
sprintf('Class %s does not exist.', $handler) |
29
|
|
|
); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (false === in_array(EventHandler::class, class_implements($handler, true))) { |
33
|
|
|
throw new RuntimeException( |
34
|
|
|
sprintf('Class %s does not implement the %s interface.', $handler, EventHandler::class) |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$priority = EventHandlerPriority::LOW_PRIORITY; |
39
|
|
|
if (false !== in_array(EventHandlerPriority::class, class_implements($handler, true))) { |
40
|
|
|
/* @var EventHandlerPriority $handler */ |
41
|
|
|
$priority = $handler::priority(); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/* @var EventHandler $handler */ |
45
|
|
|
$this->listeners[$handler::subscribedTo()][$priority][] = $handler; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
|
|
public function handlerName(Event $event) : array |
53
|
|
|
{ |
54
|
|
|
$eventClass = get_class($event); |
55
|
|
|
|
56
|
|
|
if (empty($this->listeners[$eventClass])) { |
57
|
|
|
throw new RuntimeException(sprintf('Event %s has no EventHandler defined.', $eventClass)); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
ksort($this->listeners[$eventClass], SORT_NUMERIC); |
61
|
|
|
|
62
|
|
|
return $this->listeners[$eventClass]; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|