EventListenerHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiistack\Events;
6
7
use Psr\Container\ContainerInterface;
8
use ReflectionClass;
9
use RustamWin\Attributes\Dto\ResolvedAttribute;
10
use RustamWin\Attributes\Handler\AttributeHandlerInterface;
11
use Yiisoft\EventDispatcher\Provider\ListenerCollection;
12
use Yiisoft\Injector\Injector;
13
use Yiistack\Events\Attribute\Listener;
14
15
final class EventListenerHandler implements AttributeHandlerInterface
16
{
17
    private ListenerCollection $listenerCollection;
18
    private Injector $injector;
19 1
    public function __construct(private ContainerInterface $container)
20
    {
21 1
        $this->listenerCollection = new ListenerCollection();
22 1
        $this->injector = new Injector($this->container);
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28 1
    public function handle(ReflectionClass $class, iterable $attributes): void
29
    {
30 1
        foreach ($attributes as $attribute) {
31 1
            if ($attribute->getAttribute() instanceof Listener) {
32
                /** @var ResolvedAttribute<Listener, \ReflectionFunction|\ReflectionMethod> $attribute */
33 1
                $this->listenerCollection = $this->listenerCollection->add(
34 1
                    $this->prepareListener($attribute->getReflectionTarget()),
35 1
                    $attribute->getAttribute()->getEvent()
36
                );
37
            }
38
        }
39
    }
40
41 1
    public function getListenerCollection(): ListenerCollection
42
    {
43 1
        return $this->listenerCollection;
44
    }
45
46 1
    private function prepareListener(\ReflectionFunction|\ReflectionMethod $reflection): callable
47
    {
48 1
        if ($reflection instanceof \ReflectionMethod) {
49 1
            $listener = [$this->container->get($reflection->getDeclaringClass()->getName()), $reflection->getName()];
50
        } else {
51
            $listener = $reflection->getClosure();
52
        }
53 1
        return function (object $event) use ($listener): mixed {
54
            /** @var callable $listener */
55
            return $this->injector->invoke(
56
                $listener,
57
                [$event]
58
            );
59
        };
60
    }
61
}