XmlDumper.php 16 KB

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