XmlDumper.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Dumper;
  11. use Symfony\Component\DependencyInjection\Alias;
  12. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  13. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  14. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  15. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. use Symfony\Component\DependencyInjection\Definition;
  18. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  19. use Symfony\Component\DependencyInjection\Parameter;
  20. use Symfony\Component\DependencyInjection\Reference;
  21. use Symfony\Component\ExpressionLanguage\Expression;
  22. /**
  23. * XmlDumper dumps a service container as an XML string.
  24. *
  25. * @author Fabien Potencier <fabien@symfony.com>
  26. * @author Martin Hasoň <martin.hason@gmail.com>
  27. */
  28. class XmlDumper extends Dumper
  29. {
  30. /**
  31. * @var \DOMDocument
  32. */
  33. private $document;
  34. /**
  35. * Dumps the service container as an XML string.
  36. *
  37. * @return string An xml string representing of the service container
  38. */
  39. public function dump(array $options = [])
  40. {
  41. $this->document = new \DOMDocument('1.0', 'utf-8');
  42. $this->document->formatOutput = true;
  43. $container = $this->document->createElementNS('http://symfony.com/schema/dic/services', 'container');
  44. $container->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  45. $container->setAttribute('xsi:schemaLocation', 'http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd');
  46. $this->addParameters($container);
  47. $this->addServices($container);
  48. $this->document->appendChild($container);
  49. $xml = $this->document->saveXML();
  50. $this->document = null;
  51. return $this->container->resolveEnvPlaceholders($xml);
  52. }
  53. private function addParameters(\DOMElement $parent)
  54. {
  55. $data = $this->container->getParameterBag()->all();
  56. if (!$data) {
  57. return;
  58. }
  59. if ($this->container->isCompiled()) {
  60. $data = $this->escape($data);
  61. }
  62. $parameters = $this->document->createElement('parameters');
  63. $parent->appendChild($parameters);
  64. $this->convertParameters($data, 'parameter', $parameters);
  65. }
  66. private function addMethodCalls(array $methodcalls, \DOMElement $parent)
  67. {
  68. foreach ($methodcalls as $methodcall) {
  69. $call = $this->document->createElement('call');
  70. $call->setAttribute('method', $methodcall[0]);
  71. if (\count($methodcall[1])) {
  72. $this->convertParameters($methodcall[1], 'argument', $call);
  73. }
  74. if ($methodcall[2] ?? false) {
  75. $call->setAttribute('returns-clone', 'true');
  76. }
  77. $parent->appendChild($call);
  78. }
  79. }
  80. private function addService(Definition $definition, ?string $id, \DOMElement $parent)
  81. {
  82. $service = $this->document->createElement('service');
  83. if (null !== $id) {
  84. $service->setAttribute('id', $id);
  85. }
  86. if ($class = $definition->getClass()) {
  87. if ('\\' === substr($class, 0, 1)) {
  88. $class = substr($class, 1);
  89. }
  90. $service->setAttribute('class', $class);
  91. }
  92. if (!$definition->isShared()) {
  93. $service->setAttribute('shared', 'false');
  94. }
  95. if (!$definition->isPrivate()) {
  96. $service->setAttribute('public', $definition->isPublic() ? 'true' : 'false');
  97. }
  98. if ($definition->isSynthetic()) {
  99. $service->setAttribute('synthetic', 'true');
  100. }
  101. if ($definition->isLazy()) {
  102. $service->setAttribute('lazy', 'true');
  103. }
  104. if (null !== $decoratedService = $definition->getDecoratedService()) {
  105. [$decorated, $renamedId, $priority] = $decoratedService;
  106. $service->setAttribute('decorates', $decorated);
  107. $decorationOnInvalid = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  108. if (\in_array($decorationOnInvalid, [ContainerInterface::IGNORE_ON_INVALID_REFERENCE, ContainerInterface::NULL_ON_INVALID_REFERENCE], true)) {
  109. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE === $decorationOnInvalid ? 'null' : 'ignore';
  110. $service->setAttribute('decoration-on-invalid', $invalidBehavior);
  111. }
  112. if (null !== $renamedId) {
  113. $service->setAttribute('decoration-inner-name', $renamedId);
  114. }
  115. if (0 !== $priority) {
  116. $service->setAttribute('decoration-priority', $priority);
  117. }
  118. }
  119. foreach ($definition->getTags() as $name => $tags) {
  120. foreach ($tags as $attributes) {
  121. $tag = $this->document->createElement('tag');
  122. $tag->setAttribute('name', $name);
  123. foreach ($attributes as $key => $value) {
  124. $tag->setAttribute($key, $value);
  125. }
  126. $service->appendChild($tag);
  127. }
  128. }
  129. if ($definition->getFile()) {
  130. $file = $this->document->createElement('file');
  131. $file->appendChild($this->document->createTextNode($definition->getFile()));
  132. $service->appendChild($file);
  133. }
  134. if ($parameters = $definition->getArguments()) {
  135. $this->convertParameters($parameters, 'argument', $service);
  136. }
  137. if ($parameters = $definition->getProperties()) {
  138. $this->convertParameters($parameters, 'property', $service, 'name');
  139. }
  140. $this->addMethodCalls($definition->getMethodCalls(), $service);
  141. if ($callable = $definition->getFactory()) {
  142. $factory = $this->document->createElement('factory');
  143. if (\is_array($callable) && $callable[0] instanceof Definition) {
  144. $this->addService($callable[0], null, $factory);
  145. $factory->setAttribute('method', $callable[1]);
  146. } elseif (\is_array($callable)) {
  147. if (null !== $callable[0]) {
  148. $factory->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]);
  149. }
  150. $factory->setAttribute('method', $callable[1]);
  151. } else {
  152. $factory->setAttribute('function', $callable);
  153. }
  154. $service->appendChild($factory);
  155. }
  156. if ($definition->isDeprecated()) {
  157. $deprecated = $this->document->createElement('deprecated');
  158. $deprecated->appendChild($this->document->createTextNode($definition->getDeprecationMessage('%service_id%')));
  159. $service->appendChild($deprecated);
  160. }
  161. if ($definition->isAutowired()) {
  162. $service->setAttribute('autowire', 'true');
  163. }
  164. if ($definition->isAutoconfigured()) {
  165. $service->setAttribute('autoconfigure', 'true');
  166. }
  167. if ($definition->isAbstract()) {
  168. $service->setAttribute('abstract', 'true');
  169. }
  170. if ($callable = $definition->getConfigurator()) {
  171. $configurator = $this->document->createElement('configurator');
  172. if (\is_array($callable) && $callable[0] instanceof Definition) {
  173. $this->addService($callable[0], null, $configurator);
  174. $configurator->setAttribute('method', $callable[1]);
  175. } elseif (\is_array($callable)) {
  176. $configurator->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]);
  177. $configurator->setAttribute('method', $callable[1]);
  178. } else {
  179. $configurator->setAttribute('function', $callable);
  180. }
  181. $service->appendChild($configurator);
  182. }
  183. $parent->appendChild($service);
  184. }
  185. private function addServiceAlias(string $alias, Alias $id, \DOMElement $parent)
  186. {
  187. $service = $this->document->createElement('service');
  188. $service->setAttribute('id', $alias);
  189. $service->setAttribute('alias', $id);
  190. if (!$id->isPrivate()) {
  191. $service->setAttribute('public', $id->isPublic() ? 'true' : 'false');
  192. }
  193. if ($id->isDeprecated()) {
  194. $deprecated = $this->document->createElement('deprecated');
  195. $deprecated->appendChild($this->document->createTextNode($id->getDeprecationMessage('%alias_id%')));
  196. $service->appendChild($deprecated);
  197. }
  198. $parent->appendChild($service);
  199. }
  200. private function addServices(\DOMElement $parent)
  201. {
  202. $definitions = $this->container->getDefinitions();
  203. if (!$definitions) {
  204. return;
  205. }
  206. $services = $this->document->createElement('services');
  207. foreach ($definitions as $id => $definition) {
  208. $this->addService($definition, $id, $services);
  209. }
  210. $aliases = $this->container->getAliases();
  211. foreach ($aliases as $alias => $id) {
  212. while (isset($aliases[(string) $id])) {
  213. $id = $aliases[(string) $id];
  214. }
  215. $this->addServiceAlias($alias, $id, $services);
  216. }
  217. $parent->appendChild($services);
  218. }
  219. private function convertParameters(array $parameters, string $type, \DOMElement $parent, string $keyAttribute = 'key')
  220. {
  221. $withKeys = array_keys($parameters) !== range(0, \count($parameters) - 1);
  222. foreach ($parameters as $key => $value) {
  223. $element = $this->document->createElement($type);
  224. if ($withKeys) {
  225. $element->setAttribute($keyAttribute, $key);
  226. }
  227. if (\is_array($tag = $value)) {
  228. $element->setAttribute('type', 'collection');
  229. $this->convertParameters($value, $type, $element, 'key');
  230. } elseif ($value instanceof TaggedIteratorArgument || ($value instanceof ServiceLocatorArgument && $tag = $value->getTaggedIteratorArgument())) {
  231. $element->setAttribute('type', $value instanceof TaggedIteratorArgument ? 'tagged_iterator' : 'tagged_locator');
  232. $element->setAttribute('tag', $tag->getTag());
  233. if (null !== $tag->getIndexAttribute()) {
  234. $element->setAttribute('index-by', $tag->getIndexAttribute());
  235. if (null !== $tag->getDefaultIndexMethod()) {
  236. $element->setAttribute('default-index-method', $tag->getDefaultIndexMethod());
  237. }
  238. if (null !== $tag->getDefaultPriorityMethod()) {
  239. $element->setAttribute('default-priority-method', $tag->getDefaultPriorityMethod());
  240. }
  241. }
  242. } elseif ($value instanceof IteratorArgument) {
  243. $element->setAttribute('type', 'iterator');
  244. $this->convertParameters($value->getValues(), $type, $element, 'key');
  245. } elseif ($value instanceof ServiceLocatorArgument) {
  246. $element->setAttribute('type', 'service_locator');
  247. $this->convertParameters($value->getValues(), $type, $element, 'key');
  248. } elseif ($value instanceof Reference || $value instanceof ServiceClosureArgument) {
  249. $element->setAttribute('type', 'service');
  250. if ($value instanceof ServiceClosureArgument) {
  251. $element->setAttribute('type', 'service_closure');
  252. $value = $value->getValues()[0];
  253. }
  254. $element->setAttribute('id', (string) $value);
  255. $behavior = $value->getInvalidBehavior();
  256. if (ContainerInterface::NULL_ON_INVALID_REFERENCE == $behavior) {
  257. $element->setAttribute('on-invalid', 'null');
  258. } elseif (ContainerInterface::IGNORE_ON_INVALID_REFERENCE == $behavior) {
  259. $element->setAttribute('on-invalid', 'ignore');
  260. } elseif (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE == $behavior) {
  261. $element->setAttribute('on-invalid', 'ignore_uninitialized');
  262. }
  263. } elseif ($value instanceof Definition) {
  264. $element->setAttribute('type', 'service');
  265. $this->addService($value, null, $element);
  266. } elseif ($value instanceof Expression) {
  267. $element->setAttribute('type', 'expression');
  268. $text = $this->document->createTextNode(self::phpToXml((string) $value));
  269. $element->appendChild($text);
  270. } elseif (\is_string($value) && !preg_match('/^[^\x00-\x08\x0B\x0E-\x1A\x1C-\x1F\x7F]*+$/u', $value)) {
  271. $element->setAttribute('type', 'binary');
  272. $text = $this->document->createTextNode(self::phpToXml(base64_encode($value)));
  273. $element->appendChild($text);
  274. } else {
  275. if (\in_array($value, ['null', 'true', 'false'], true)) {
  276. $element->setAttribute('type', 'string');
  277. }
  278. if (\is_string($value) && (is_numeric($value) || preg_match('/^0b[01]*$/', $value) || preg_match('/^0x[0-9a-f]++$/i', $value))) {
  279. $element->setAttribute('type', 'string');
  280. }
  281. $text = $this->document->createTextNode(self::phpToXml($value));
  282. $element->appendChild($text);
  283. }
  284. $parent->appendChild($element);
  285. }
  286. }
  287. /**
  288. * Escapes arguments.
  289. */
  290. private function escape(array $arguments): array
  291. {
  292. $args = [];
  293. foreach ($arguments as $k => $v) {
  294. if (\is_array($v)) {
  295. $args[$k] = $this->escape($v);
  296. } elseif (\is_string($v)) {
  297. $args[$k] = str_replace('%', '%%', $v);
  298. } else {
  299. $args[$k] = $v;
  300. }
  301. }
  302. return $args;
  303. }
  304. /**
  305. * Converts php types to xml types.
  306. *
  307. * @param mixed $value Value to convert
  308. *
  309. * @throws RuntimeException When trying to dump object or resource
  310. */
  311. public static function phpToXml($value): string
  312. {
  313. switch (true) {
  314. case null === $value:
  315. return 'null';
  316. case true === $value:
  317. return 'true';
  318. case false === $value:
  319. return 'false';
  320. case $value instanceof Parameter:
  321. return '%'.$value.'%';
  322. case \is_object($value) || \is_resource($value):
  323. throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
  324. default:
  325. return (string) $value;
  326. }
  327. }
  328. }