Passed
Branch master (893f23)
by Olivier
10:57
created

ContainerHandlerProvider   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 27
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getHandlerForMessage() 0 13 3
A __construct() 0 6 1
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\MessageBus\PSR;
13
14
use ICanBoogie\MessageBus\HandlerProvider;
15
use ICanBoogie\MessageBus\NotFound;
16
use Psr\Container\ContainerInterface;
17
use Psr\Container\NotFoundExceptionInterface;
18
19
use function get_class;
20
21
class ContainerHandlerProvider implements HandlerProvider
22
{
23
    /**
24
     * @param array<string, string> $handlers
25
     *     Where _key_ is a message class and _value_ the service identifier of its handler.
26
     */
27
    public function __construct(
28
        private ContainerInterface $container,
29
        private array $handlers
30
    ) {
31
        $this->container = $container;
32
        $this->handlers = $handlers;
33
    }
34
35
    public function getHandlerForMessage(object $message): callable
36
    {
37
        $class = get_class($message);
38
        $id = $this->handlers[$class] ?? null;
39
40
        if (!$id) {
41
            throw new NotFound("No handler for messages of type `$class`.");
42
        }
43
44
        try {
45
            return $this->container->get($id); // @phpstan-ignore-line
46
        } catch (NotFoundExceptionInterface $e) {
47
            throw new NotFound("No handler for messages of type `$class`.", $e);
48
        }
49
    }
50
}
51