Passed
Push — master ( 990fe5...10b36f )
by Alexander
02:04 queued 10s
created

EventConfigurator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 21
c 3
b 0
f 0
dl 0
loc 36
ccs 15
cts 20
cp 0.75
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B registerListeners() 0 24 9
1
<?php
2
3
namespace Yiisoft\Yii\Web\Config;
4
5
use Psr\Container\ContainerInterface;
6
use Yiisoft\EventDispatcher\Provider\AbstractProviderConfigurator;
7
use Yiisoft\EventDispatcher\Provider\Provider;
8
use Yiisoft\Injector\Injector;
9
10
class EventConfigurator extends AbstractProviderConfigurator
11
{
12
    private Provider $listenerProvider;
13
14
    private ContainerInterface $container;
15
16 2
    public function __construct(Provider $listenerProvider, ContainerInterface $container)
17
    {
18 2
        $this->listenerProvider = $listenerProvider;
19 2
        $this->container = $container;
20 2
    }
21
22 2
    public function registerListeners(array $eventsListeners): void
23
    {
24 2
        foreach ($eventsListeners as $eventName => $listeners) {
25 2
            if (!is_string($eventName)) {
26
                throw new \RuntimeException('Incorrect event listener format. Format with event name must be used.');
27
            }
28
29 2
            if (!is_array($listeners)) {
30
                $type = is_callable($listeners) ? 'callable' : gettype($listeners);
31
                throw new \RuntimeException("Event listeners for $eventName must be an array, $type detected.");
32
            }
33 2
            foreach ($listeners as $callable) {
34 2
                if (!is_callable($callable)) {
35
                    $type = gettype($listeners);
36
                    throw new \RuntimeException("Listener must be a callable. $type given.");
37
                }
38 2
                if (is_array($callable) && !is_object($callable[0])) {
39 1
                    $callable = [$this->container->get($callable[0]), $callable[1]];
40
                }
41
42 2
                $this->listenerProvider
43 2
                    ->attach(
44 2
                        fn ($event) => (new Injector($this->container))->invoke($callable, [$event]),
45
                        $eventName
46
                    );
47
            }
48
        }
49 2
    }
50
}
51