Passed
Pull Request — master (#238)
by Alexander
02:41
created

EventConfigurator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 33
c 0
b 0
f 0
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
B registerListeners() 0 18 8
1
<?php
2
3
namespace Yiisoft\Yii\Web\Config;
4
5
use Psr\Container\ContainerInterface;
6
use Psr\EventDispatcher\ListenerProviderInterface;
7
use Yiisoft\EventDispatcher\Provider\Provider;
8
9
class EventConfigurator
10
{
11
    private ListenerProviderInterface $listenerProvider;
12
13
    private ContainerInterface $container;
14
15
    public function __construct(ListenerProviderInterface $listenerProvider, ContainerInterface $container)
16
    {
17
        if (!($listenerProvider instanceof Provider)) {
18
            throw new \InvalidArgumentException('Listener provider must be an instance of \Yiisoft\EventDispatcher\Provider.');
19
        }
20
        $this->listenerProvider = $listenerProvider;
21
        $this->container = $container;
22
    }
23
24
    public function registerListeners(array $listeners): void
25
    {
26
        foreach ($listeners as $event => $listener) {
27
            if (is_string($event)) {
28
                foreach ($listener as $callable) {
29
                    if (!is_callable($callable)) {
30
                        throw new \RuntimeException('Listener must be a callable.');
31
                    }
32
                    if (is_array($callable) && !is_object($callable[0])) {
33
                        $callable = [$this->container->get($callable[0]), $callable[1]];
34
                    }
35
                    $this->listenerProvider->attach($callable, $event);
0 ignored issues
show
Bug introduced by
The method attach() does not exist on Psr\EventDispatcher\ListenerProviderInterface. It seems like you code against a sub-type of Psr\EventDispatcher\ListenerProviderInterface such as Yiisoft\EventDispatcher\Provider\Provider or Yiisoft\EventDispatcher\Provider\CompositeProvider. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

35
                    $this->listenerProvider->/** @scrutinizer ignore-call */ 
36
                                             attach($callable, $event);
Loading history...
36
                }
37
            } else {
38
                if (!is_callable($listener)) {
39
                    throw new \RuntimeException('Listener must be a callable.');
40
                }
41
                $this->listenerProvider->attach($listener);
42
            }
43
        }
44
    }
45
}
46