|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace SaschaEgerer\PhpstanTypo3\Service; |
| 5 | + |
| 6 | +use SaschaEgerer\PhpstanTypo3\Contract\ServiceMapFactoryInterface; |
| 7 | +use SaschaEgerer\PhpstanTypo3\Contract\ServiceMapInterface; |
| 8 | +use SimpleXMLElement; |
| 9 | + |
| 10 | +final class XmlServiceMapFactory implements ServiceMapFactoryInterface |
| 11 | +{ |
| 12 | + private ?string $containerXmlPath; |
| 13 | + |
| 14 | + public function __construct(?string $containerXmlPath) |
| 15 | + { |
| 16 | + $this->containerXmlPath = $containerXmlPath; |
| 17 | + } |
| 18 | + |
| 19 | + public function create(): ServiceMapInterface |
| 20 | + { |
| 21 | + if ($this->containerXmlPath === null) { |
| 22 | + return new FakeServiceMap(); |
| 23 | + } |
| 24 | + |
| 25 | + if(!file_exists($this->containerXmlPath)) { |
| 26 | + throw ServiceDefinitionFileException::notFound($this->containerXmlPath); |
| 27 | + } |
| 28 | + |
| 29 | + $xml = @simplexml_load_file($this->containerXmlPath); |
| 30 | + |
| 31 | + if($xml === false) { |
| 32 | + throw ServiceDefinitionFileException::parseError($this->containerXmlPath); |
| 33 | + } |
| 34 | + |
| 35 | + /** @var ServiceDefinition[] $serviceDefinitions */ |
| 36 | + $serviceDefinitions = []; |
| 37 | + /** @var ServiceDefinition[] $aliases */ |
| 38 | + $aliases = []; |
| 39 | + foreach ($xml->services->service as $def) { |
| 40 | + /** @var SimpleXMLElement $attrs */ |
| 41 | + $attrs = $def->attributes(); |
| 42 | + if (!isset($attrs->id)) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + $serviceDefinition = new ServiceDefinition( |
| 47 | + strpos((string) $attrs->id, '.') === 0 ? substr((string) $attrs->id, 1) : (string) $attrs->id, |
| 48 | + isset($attrs->class) ? (string) $attrs->class : null, |
| 49 | + isset($attrs->public) && (string) $attrs->public === 'true', |
| 50 | + isset($attrs->synthetic) && (string) $attrs->synthetic === 'true', |
| 51 | + isset($attrs->alias) ? (string) $attrs->alias : null |
| 52 | + ); |
| 53 | + |
| 54 | + if ($serviceDefinition->getAlias() !== null) { |
| 55 | + $aliases[] = $serviceDefinition; |
| 56 | + } else { |
| 57 | + $serviceDefinitions[$serviceDefinition->getId()] = $serviceDefinition; |
| 58 | + } |
| 59 | + } |
| 60 | + foreach ($aliases as $serviceDefinition) { |
| 61 | + $alias = $serviceDefinition->getAlias(); |
| 62 | + if ($alias !== null && !isset($serviceDefinitions[$alias])) { |
| 63 | + continue; |
| 64 | + } |
| 65 | + $id = $serviceDefinition->getId(); |
| 66 | + $serviceDefinitions[$id] = new ServiceDefinition( |
| 67 | + $id, |
| 68 | + $serviceDefinitions[$alias]->getClass(), |
| 69 | + $serviceDefinition->isPublic(), |
| 70 | + $serviceDefinition->isSynthetic(), |
| 71 | + $alias |
| 72 | + ); |
| 73 | + } |
| 74 | + |
| 75 | + return new ServiceMap($serviceDefinitions); |
| 76 | + } |
| 77 | +} |
0 commit comments