ListenerCollectionFactory   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 41
ccs 22
cts 22
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A create() 0 30 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Event;
6
7
use Yiisoft\EventDispatcher\Provider\ListenerCollection;
8
use Yiisoft\Injector\Injector;
9
10
use function is_string;
11
12
final class ListenerCollectionFactory
13
{
14 8
    public function __construct(
15
        private Injector $injector,
16
        private CallableFactory $callableFactory,
17
    ) {
18 8
    }
19
20
    /**
21
     * @param array $eventListeners Event listener list in format ['eventName1' => [$listener1, $listener2, ...]]
22
     */
23 8
    public function create(array $eventListeners): ListenerCollection
24
    {
25 8
        $listenerCollection = new ListenerCollection();
26
27 8
        foreach ($eventListeners as $eventName => $listeners) {
28 6
            if (!is_string($eventName)) {
29 1
                throw new InvalidEventConfigurationFormatException(
30 1
                    'Incorrect event listener format. Format with event name must be used.'
31 1
                );
32
            }
33
34 5
            if (!is_iterable($listeners)) {
35 1
                $type = get_debug_type($listeners);
36
37 1
                throw new InvalidEventConfigurationFormatException(
38 1
                    "Event listeners for $eventName must be an iterable, $type given."
39 1
                );
40
            }
41
42 4
            foreach ($listeners as $callable) {
43 4
                $listener =
44 4
                    fn (object $event): mixed => $this->injector->invoke(
45 4
                        $this->callableFactory->create($callable),
46 4
                        [$event]
47 4
                    );
48 4
                $listenerCollection = $listenerCollection->add($listener, $eventName);
49
            }
50
        }
51
52 6
        return $listenerCollection;
53
    }
54
}
55