Passed
Pull Request — master (#1)
by Alex
08:52
created

EventDispatcherProviderTrait::getEventDispatcher()   A

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\Exception\ServiceNotFoundException;
9
use Laminas\ServiceManager\ServiceLocatorInterface;
10
use Psr\EventDispatcher\EventDispatcherInterface;
11
12
/**
13
 * @author  Alex Patterson <[email protected]>
14
 * @package Arp\LaminasEvent\Factory
15
 */
16
trait EventDispatcherProviderTrait
17
{
18
    /**
19
     * @param ServiceLocatorInterface                           $container
20
     * @param string|array<mixed>|EventDispatcherInterface|null $eventDispatcher
21
     * @param string                                            $serviceName
22
     *
23
     * @return EventDispatcherInterface
24
     *
25
     * @throws ServiceNotCreatedException
26
     * @throws ServiceNotFoundException
27
     */
28
    private function getEventDispatcher(
29
        ServiceLocatorInterface $container,
30
        $eventDispatcher,
31
        string $serviceName
32
    ): EventDispatcherInterface {
33
        if (null === $eventDispatcher) {
34
            $eventDispatcher = [];
35
        }
36
37
        if (is_array($eventDispatcher)) {
38
            $eventDispatcher = $container->build(EventDispatcherInterface::class, $eventDispatcher);
39
        }
40
41
        if (is_string($eventDispatcher)) {
42
            $eventDispatcher = $container->get($eventDispatcher);
43
        }
44
45
        if (!$eventDispatcher instanceof EventDispatcherInterface) {
46
            throw new ServiceNotCreatedException(
47
                sprintf(
48
                    'The event dispatcher must be an object of type \'%s\'; \'%s\' provided for service \'%s\'',
49
                    EventDispatcherInterface::class,
50
                    is_object($eventDispatcher) ? get_class($eventDispatcher) : gettype($eventDispatcher),
51
                    $serviceName
52
                )
53
            );
54
        }
55
56
        return $eventDispatcher;
57
    }
58
}
59