Completed
Push — master ( 3e3d3c...053aa5 )
by Olivier
01:44
created

ContainerHandlerProvider   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 39
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getHandlerForMessage() 0 15 3
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
     * @var ContainerInterface
25
     */
26
    private $container;
27
28
    /**
29
     * @var array<string, string>
30
     */
31
    private $handlers;
32
33
    /**
34
     * @param array<string, string> $mapping
35
     *   An array of key/value pairs where _key_ is a message class and _value_ the service
36
     *   identifier of its handler.
37
     */
38
    public function __construct(ContainerInterface $container, array $mapping)
39
    {
40
        $this->handlers = $mapping;
41
        $this->container = $container;
42
    }
43
44
    public function getHandlerForMessage(object $message): callable
45
    {
46
        $class = get_class($message);
47
        $id = $this->handlers[$class] ?? null;
48
49
        if (!$id) {
50
            throw new NotFound("No handler for messages of type `$class`.");
51
        }
52
53
        try {
54
            return $this->container->get($id);
55
        } catch (NotFoundExceptionInterface $e) {
56
            throw new NotFound("No handler for messages of type `$class`.", $e);
0 ignored issues
show
Documentation introduced by
$e is of type object<Psr\Container\NotFoundExceptionInterface>, but the function expects a null|object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
57
        }
58
    }
59
}
60