EventDispatcherProviderTrait::getEventDispatcher()   A
last analyzed

Complexity

Conditions 6
Paths 16

Size

Total Lines 29
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 14
c 1
b 0
f 1
nc 16
nop 3
dl 0
loc 29
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasEvent\Factory;
6
7
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
8
use Laminas\ServiceManager\ServiceLocatorInterface;
9
use Psr\Container\ContainerExceptionInterface;
10
use Psr\Container\NotFoundExceptionInterface;
11
use Psr\EventDispatcher\EventDispatcherInterface;
12
13
trait EventDispatcherProviderTrait
14
{
15
    /**
16
     * @param string|array<mixed>|EventDispatcherInterface|null $eventDispatcher
17
     *
18
     * @throws ServiceNotCreatedException
19
     * @throws ContainerExceptionInterface
20
     * @throws NotFoundExceptionInterface
21
     */
22
    private function getEventDispatcher(
23
        ServiceLocatorInterface $container,
24
        $eventDispatcher,
25
        string $serviceName
26
    ): EventDispatcherInterface {
27
        if (null === $eventDispatcher) {
28
            $eventDispatcher = [];
29
        }
30
31
        if (is_array($eventDispatcher)) {
32
            $eventDispatcher = $container->build(EventDispatcherInterface::class, $eventDispatcher);
33
        }
34
35
        if (is_string($eventDispatcher)) {
36
            $eventDispatcher = $container->get($eventDispatcher);
37
        }
38
39
        if (!$eventDispatcher instanceof EventDispatcherInterface) {
40
            throw new ServiceNotCreatedException(
41
                sprintf(
42
                    'The event dispatcher must be an object of type \'%s\'; \'%s\' provided for service \'%s\'',
43
                    EventDispatcherInterface::class,
44
                    is_object($eventDispatcher) ? get_class($eventDispatcher) : gettype($eventDispatcher),
45
                    $serviceName
46
                )
47
            );
48
        }
49
50
        return $eventDispatcher;
51
    }
52
}
53