EventListenerHandler   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
c 2
b 0
f 0
dl 0
loc 43
ccs 15
cts 18
cp 0.8333
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getListenerCollection() 0 3 1
A __construct() 0 4 1
A handle() 0 8 3
A prepareListener() 0 12 2
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
}