ListenerCollectionFactory::create()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 30
ccs 20
cts 20
cp 1
crap 5
rs 9.4222
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