DefinitionLoader::loadDefinitions()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.2888
c 0
b 0
f 0
cc 5
nc 5
nop 1
1
<?php
2
3
namespace RDV\SymfonyContainerMocks\DependencyInjection;
4
5
use Symfony\Component\DependencyInjection\Container;
6
7
class DefinitionLoader
8
{
9
    /** @var array */
10
    protected static $definitions = [];
11
12
    /**
13
     * @param Container $container
14
     */
15
    protected static function loadDefinitions(Container $container)
16
    {
17
        if (empty(self::$definitions)) {
18
            if (!$container->hasParameter('debug.container.dump')) {
19
                throw new \BadMethodCallException('Class autodetection works only with "debug" enabled');
20
            }
21
22
            $dump = $container->getParameter('debug.container.dump');
23
            $xml = simplexml_load_file($dump);
24
25
            foreach ($xml->services->service as $service) {
26
                $attributes = $service->attributes();
27
                $id = (string)$attributes['id'];
28
                $class = (string)$attributes['class'];
29
                if (!empty($class)) {
30
                    self::$definitions[$id] = $class;
31
                }
32
            }
33
        }
34
    }
35
36
    /**
37
     * Unload all cached definitions
38
     */
39
    public static function unload()
40
    {
41
        self::$definitions = [];
42
    }
43
44
    /**
45
     * @param string $service
46
     * @param Container $container
47
     * @return string mixed
48
     */
49
    public static function getClassName($service, Container $container)
50
    {
51
        self::loadDefinitions($container);
52
53
        if (empty(self::$definitions[$service])) {
54
            throw new \InvalidArgumentException(
55
                sprintf('Service "%s" is not defined or class name cannot be detected', $service)
56
            );
57
        }
58
59
        return self::$definitions[$service];
60
    }
61
}
62
63