ClassMultiMap::all()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
namespace Skrz\Bundle\AutowiringBundle\DependencyInjection;
3
4
use Skrz\Bundle\AutowiringBundle\Exception\MultipleValuesException;
5
use Skrz\Bundle\AutowiringBundle\Exception\NoValueException;
6
use Symfony\Component\DependencyInjection\ContainerBuilder;
7
8
/**
9
 * Maps from class name, all its parents, and implemented interfaces to certain value
10
 *
11
 * @author Jakub Kulhan <[email protected]>
12
 */
13
class ClassMultiMap
14
{
15
16
	/** @var ContainerBuilder */
17
	private $containerBuilder;
18
19
	/** @var string[][] */
20
	private $classes = [];
21
22 16
	public function __construct(ContainerBuilder $containerBuilder)
23
	{
24 16
		$this->containerBuilder = $containerBuilder;
25 16
	}
26
27
	/**
28
	 * @param string $className
29
	 * @param string $value
30
	 * @return void
31
	 */
32 13
	public function put(string $className, string $value)
33
	{
34 13
		$reflectionClass = $this->containerBuilder->getReflectionClass($className, false);
35 13
		if ($reflectionClass === null) {
36
			return;
37
		}
38
39 13
		foreach ($reflectionClass->getInterfaceNames() as $interfaceName) {
40 13
			if (!isset($this->classes[$interfaceName])) {
41 13
				$this->classes[$interfaceName] = [];
42
			}
43 13
			$this->classes[$interfaceName][] = $value;
44
		}
45
46
		do {
47 13
			if (!isset($this->classes[$reflectionClass->getName()])) {
48 13
				$this->classes[$reflectionClass->getName()] = [];
49
			}
50 13
			$this->classes[$reflectionClass->getName()][] = $value;
51 13
		} while ($reflectionClass = $reflectionClass->getParentClass());
52 13
	}
53
54
	/**
55
	 * @param string $className
56
	 * @return string
57
	 */
58 9
	public function getSingle(string $className): string
59
	{
60 9
		if (!isset($this->classes[$className])) {
61 2
			throw new NoValueException(sprintf("Key '%s'.", $className));
62
		}
63
64 7
		$values = $this->classes[$className];
65
66 7
		if (count($values) > 1) {
67 2
			throw new MultipleValuesException(sprintf("Key '%s' - values: '%s'", $className, json_encode($values)));
68
		}
69
70 5
		return reset($values);
71
	}
72
73
	/**
74
	 * @param string $className
75
	 * @return string[]
76
	 */
77 2
	public function getMulti(string $className): array
78
	{
79 2
		if (!isset($this->classes[$className])) {
80 1
			return [];
81
		}
82
83 1
		return $this->classes[$className];
84
	}
85
86
	/**
87
	 * @return string[][]
88
	 */
89 4
	public function all(): array
90
	{
91 4
		return $this->classes;
92
	}
93
94
}
95