Passed
Push — main ( 51c6aa...64863d )
by Thierry
01:49
created

Container::getService()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 8
c 2
b 0
f 0
nc 10
nop 1
dl 0
loc 17
rs 8.8333
1
<?php
2
3
namespace Lagdo\Symfony\Facades;
4
5
use Symfony\Component\DependencyInjection\ContainerInterface;
6
use Symfony\Component\DependencyInjection\ServiceLocator;
7
8
final class Container
9
{
10
    /**
11
     * @var array
12
     */
13
    private static $services = [];
14
15
    /**
16
     * @var ContainerInterface
17
     */
18
    protected static $container = null;
19
20
    /**
21
     * @var ServiceLocator
22
     */
23
    protected static $locator = null;
24
25
    /**
26
     * Get a service using the container or the locator.
27
     *
28
     * @param string $serviceId
29
     *
30
     * @return mixed|null
31
     */
32
    public static function getService(string $serviceId)
33
    {
34
        $service = isset(self::$services[$serviceId]) ? self::$services[$serviceId] : null;
35
        if($service === null)
36
        {
37
            $service = self::$container->get($serviceId, ContainerInterface::NULL_ON_INVALID_REFERENCE);
38
            if($service === null && self::$locator !== null && self::$locator->has($serviceId))
39
            {
40
                $service = self::$locator->get($serviceId);
41
            }
42
            // If a service is found, save it locally.
43
            if($service !== null)
44
            {
45
                self::$services[$serviceId] = $service;
46
            }
47
        }
48
        return $service;
49
    }
50
51
    /**
52
     * Set the container and locator.
53
     *
54
     * @param ContainerInterface $container
55
     *
56
     * @return void
57
     */
58
    public static function init(ContainerInterface $container)
59
    {
60
        self::$services = [];
61
        self::$container = $container;
62
        self::$locator = self::getService('lagdo.facades.service_locator');
63
    }
64
}
65