ContainerAwareCommandHandlerLocator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 51
rs 10
c 1
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getHandlers() 0 24 6
A __construct() 0 5 1
1
<?php
2
3
/*
4
 * cqrs-symfony-messenger (https://github.com/phpgears/cqrs-symfony-messenger).
5
 * CQRS implementation with Symfony's Messenger.
6
 *
7
 * @license MIT
8
 * @link https://github.com/phpgears/cqrs-symfony-messenger
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Gears\CQRS\Symfony\Messenger;
15
16
use Gears\CQRS\Command;
17
use Gears\CQRS\CommandHandler;
18
use Gears\CQRS\Exception\InvalidCommandHandlerException;
19
use Psr\Container\ContainerInterface;
20
use Symfony\Component\Messenger\Envelope;
21
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
22
23
class ContainerAwareCommandHandlerLocator extends CommandHandlerLocator
24
{
25
    /**
26
     * PSR container.
27
     *
28
     * @var ContainerInterface
29
     */
30
    private $container;
31
32
    /**
33
     * ContainerAwareCommandHandlerLocator constructor.
34
     *
35
     * @param ContainerInterface $container
36
     * @param mixed[]            $handlers
37
     */
38
    public function __construct(ContainerInterface $container, array $handlers)
39
    {
40
        $this->container = $container;
41
42
        parent::__construct($handlers);
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     *
48
     * @throws InvalidCommandHandlerException
49
     */
50
    public function getHandlers(Envelope $envelope): iterable
51
    {
52
        $seen = [];
53
54
        foreach ($this->getCommandMap($envelope) as $type) {
55
            foreach ($this->handlersMap[$type] ?? [] as $alias => $handler) {
56
                $handler = $this->container->get($handler);
57
58
                if (!$handler instanceof CommandHandler) {
59
                    throw new InvalidCommandHandlerException(\sprintf(
60
                        'Command handler must implement %s interface, %s given.',
61
                        CommandHandler::class,
62
                        \is_object($handler) ? \get_class($handler) : \gettype($handler)
63
                    ));
64
                }
65
66
                $handlerCallable = function (Command $command) use ($handler): void {
67
                    $handler->handle($command);
68
                };
69
70
                if (!\in_array($handlerCallable, $seen, true)) {
71
                    $seen[] = $handlerCallable;
72
73
                    yield $alias => new HandlerDescriptor($handlerCallable);
74
                }
75
            }
76
        }
77
    }
78
}
79