Passed
Push — master ( f68793...1e735e )
by Olivier
10:02
created

HandlerProviderWithContainer   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 24
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getHandlerForMessage() 0 10 2
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\HandlerNotFound;
15
use ICanBoogie\MessageBus\HandlerProvider;
16
use Psr\Container\ContainerInterface;
17
use Psr\Container\NotFoundExceptionInterface;
18
19
class HandlerProviderWithContainer implements HandlerProvider
20
{
21
    /**
22
     * @param array<class-string, string> $messageToHandler
23
     *     Where _key_ is a message class and _value_ the service identifier of its handler.
24
     */
25
    public function __construct(
26
        private ContainerInterface $container,
27
        private array $messageToHandler
28
    ) {
29
        $this->container = $container;
30
        $this->messageToHandler = $messageToHandler;
31
    }
32
33
    public function getHandlerForMessage(object $message): callable
34
    {
35
        $class = $message::class;
36
        $id = $this->messageToHandler[$class]
37
            ?? throw new HandlerNotFound("No handler for messages of type `$class`.");
38
39
        try {
40
            return $this->container->get($id); // @phpstan-ignore-line
41
        } catch (NotFoundExceptionInterface $e) {
42
            throw new HandlerNotFound("No handler for messages of type `$class`.", $e);
43
        }
44
    }
45
}
46