-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MessageHandlerProvider.php
54 lines (45 loc) · 1.4 KB
/
MessageHandlerProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Cqrs;
use SonsOfPHP\Component\Cqrs\Exception\NoHandlerFoundException;
use SonsOfPHP\Contract\Cqrs\MessageHandlerProviderInterface;
/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class MessageHandlerProvider implements MessageHandlerProviderInterface
{
private array $handlers = [];
/**
* Register a command with a command handler
*
* Usage:
* $cmd = new CreateUser();
* $handler = new CreateUserHandler();
* $provider->register($cmd, $handler);
* ---
* $handler = new CreateUserHandler();
* $provider->register(CreateUser::class, $handler);
* ---
* $provider->register(CreateUser::class, function (CreateUser $cmd) {});
*/
public function add(string|object $message, callable $handler): void
{
if (is_object($message)) {
$message = $message::class;
}
$this->handlers[$message] = $handler;
}
/**
* {@inheritdoc}
*/
public function getHandlerForMessage(string|object $message): callable
{
if (is_object($message)) {
$message = $message::class;
}
if (!array_key_exists($message, $this->handlers)) {
throw new NoHandlerFoundException(sprintf('No handler for message "%s" found.', $message));
}
return $this->handlers[$message];
}
}