forked from phpstan/phpstan-symfony
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXmlServiceMapFactory.php
103 lines (85 loc) · 2.52 KB
/
XmlServiceMapFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php declare(strict_types = 1);
namespace PHPStan\Symfony;
use SimpleXMLElement;
use function count;
use function file_get_contents;
use function ksort;
use function simplexml_load_string;
use function sprintf;
use function strpos;
use function substr;
final class XmlServiceMapFactory implements ServiceMapFactory
{
private ?string $containerXml = null;
public function __construct(?string $containerXmlPath)
{
$this->containerXml = $containerXmlPath;
}
public function create(): ServiceMap
{
if ($this->containerXml === null) {
return new FakeServiceMap();
}
$fileContents = file_get_contents($this->containerXml);
if ($fileContents === false) {
throw new XmlContainerNotExistsException(sprintf('Container %s does not exist', $this->containerXml));
}
$xml = @simplexml_load_string($fileContents);
if ($xml === false) {
throw new XmlContainerNotExistsException(sprintf('Container %s cannot be parsed', $this->containerXml));
}
/** @var Service[] $services */
$services = [];
/** @var Service[] $aliases */
$aliases = [];
if (count($xml->services) > 0) {
foreach ($xml->services->service as $def) {
/** @var SimpleXMLElement $attrs */
$attrs = $def->attributes();
if (!isset($attrs->id)) {
continue;
}
$serviceTags = [];
foreach ($def->tag as $tag) {
$tagAttrs = ((array) $tag->attributes())['@attributes'] ?? [];
$tagName = $tagAttrs['name'];
unset($tagAttrs['name']);
$serviceTags[] = new ServiceTag($tagName, $tagAttrs);
}
$service = new Service(
$this->cleanServiceId((string) $attrs->id),
isset($attrs->class) ? (string) $attrs->class : null,
isset($attrs->public) && (string) $attrs->public === 'true',
isset($attrs->synthetic) && (string) $attrs->synthetic === 'true',
isset($attrs->alias) ? $this->cleanServiceId((string) $attrs->alias) : null,
$serviceTags,
);
if ($service->getAlias() !== null) {
$aliases[] = $service;
} else {
$services[$service->getId()] = $service;
}
}
}
foreach ($aliases as $service) {
$alias = $service->getAlias();
if ($alias !== null && !isset($services[$alias])) {
continue;
}
$id = $service->getId();
$services[$id] = new Service(
$id,
$services[$alias]->getClass(),
$service->isPublic(),
$service->isSynthetic(),
$alias,
);
}
ksort($services);
return new DefaultServiceMap($services);
}
private function cleanServiceId(string $id): string
{
return strpos($id, '.') === 0 ? substr($id, 1) : $id;
}
}