Passed
Push — master ( fb3de9...9fc5aa )
by Julián
04:52
created

ContainerAwareEventHandlerLocator::getHandlers()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 24
rs 9.2222
1
<?php
2
3
/*
4
 * event-symfony-messenger (https://github.com/phpgears/event-symfony-messenger).
5
 * Event bus with Symfony's Messenger.
6
 *
7
 * @license MIT
8
 * @link https://github.com/phpgears/event-symfony-messenger
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Gears\Event\Symfony\Messenger;
15
16
use Gears\Event\Event;
17
use Gears\Event\EventHandler;
18
use Gears\Event\Exception\InvalidEventHandlerException;
19
use Psr\Container\ContainerInterface;
20
use Symfony\Component\Messenger\Envelope;
21
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
22
23
class ContainerAwareEventHandlerLocator extends EventHandlerLocator
24
{
25
    /**
26
     * PSR container.
27
     *
28
     * @var ContainerInterface
29
     */
30
    private $container;
31
32
    /**
33
     * ContainerAwareEventHandlerLocator 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 InvalidEventHandlerException
49
     */
50
    public function getHandlers(Envelope $envelope): iterable
51
    {
52
        $seen = [];
53
54
        foreach ($this->getEventMap($envelope) as $type) {
55
            foreach ($this->handlersMap[$type] ?? [] as $alias => $handler) {
56
                $handler = $this->container->get($handler);
57
58
                if (!$handler instanceof EventHandler) {
59
                    throw new InvalidEventHandlerException(\sprintf(
60
                        'Event handler must implement %s interface, %s given',
61
                        EventHandler::class,
62
                        \is_object($handler) ? \get_class($handler) : \gettype($handler)
63
                    ));
64
                }
65
66
                $handlerCallable = function (Event $event) use ($handler): void {
67
                    $handler->handle($event);
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