YamlDumper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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\ArgumentInterface;
  14. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  15. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  16. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  17. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\DependencyInjection\Definition;
  20. use Symfony\Component\DependencyInjection\Exception\LogicException;
  21. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  22. use Symfony\Component\DependencyInjection\Parameter;
  23. use Symfony\Component\DependencyInjection\Reference;
  24. use Symfony\Component\ExpressionLanguage\Expression;
  25. use Symfony\Component\Yaml\Dumper as YmlDumper;
  26. use Symfony\Component\Yaml\Parser;
  27. use Symfony\Component\Yaml\Tag\TaggedValue;
  28. use Symfony\Component\Yaml\Yaml;
  29. /**
  30. * YamlDumper dumps a service container as a YAML string.
  31. *
  32. * @author Fabien Potencier <fabien@symfony.com>
  33. */
  34. class YamlDumper extends Dumper
  35. {
  36. private $dumper;
  37. /**
  38. * Dumps the service container as an YAML string.
  39. *
  40. * @return string A YAML string representing of the service container
  41. */
  42. public function dump(array $options = [])
  43. {
  44. if (!class_exists(\Symfony\Component\Yaml\Dumper::class)) {
  45. throw new LogicException('Unable to dump the container as the Symfony Yaml Component is not installed.');
  46. }
  47. if (null === $this->dumper) {
  48. $this->dumper = new YmlDumper();
  49. }
  50. return $this->container->resolveEnvPlaceholders($this->addParameters()."\n".$this->addServices());
  51. }
  52. private function addService(string $id, Definition $definition): string
  53. {
  54. $code = " $id:\n";
  55. if ($class = $definition->getClass()) {
  56. if ('\\' === substr($class, 0, 1)) {
  57. $class = substr($class, 1);
  58. }
  59. $code .= sprintf(" class: %s\n", $this->dumper->dump($class));
  60. }
  61. if (!$definition->isPrivate()) {
  62. $code .= sprintf(" public: %s\n", $definition->isPublic() ? 'true' : 'false');
  63. }
  64. $tagsCode = '';
  65. foreach ($definition->getTags() as $name => $tags) {
  66. foreach ($tags as $attributes) {
  67. $att = [];
  68. foreach ($attributes as $key => $value) {
  69. $att[] = sprintf('%s: %s', $this->dumper->dump($key), $this->dumper->dump($value));
  70. }
  71. $att = $att ? ': { '.implode(', ', $att).' }' : '';
  72. $tagsCode .= sprintf(" - %s%s\n", $this->dumper->dump($name), $att);
  73. }
  74. }
  75. if ($tagsCode) {
  76. $code .= " tags:\n".$tagsCode;
  77. }
  78. if ($definition->getFile()) {
  79. $code .= sprintf(" file: %s\n", $this->dumper->dump($definition->getFile()));
  80. }
  81. if ($definition->isSynthetic()) {
  82. $code .= " synthetic: true\n";
  83. }
  84. if ($definition->isDeprecated()) {
  85. $code .= " deprecated:\n";
  86. foreach ($definition->getDeprecation('%service_id%') as $key => $value) {
  87. if ('' !== $value) {
  88. $code .= sprintf(" %s: %s\n", $key, $this->dumper->dump($value));
  89. }
  90. }
  91. }
  92. if ($definition->isAutowired()) {
  93. $code .= " autowire: true\n";
  94. }
  95. if ($definition->isAutoconfigured()) {
  96. $code .= " autoconfigure: true\n";
  97. }
  98. if ($definition->isAbstract()) {
  99. $code .= " abstract: true\n";
  100. }
  101. if ($definition->isLazy()) {
  102. $code .= " lazy: true\n";
  103. }
  104. if ($definition->getArguments()) {
  105. $code .= sprintf(" arguments: %s\n", $this->dumper->dump($this->dumpValue($definition->getArguments()), 0));
  106. }
  107. if ($definition->getProperties()) {
  108. $code .= sprintf(" properties: %s\n", $this->dumper->dump($this->dumpValue($definition->getProperties()), 0));
  109. }
  110. if ($definition->getMethodCalls()) {
  111. $code .= sprintf(" calls:\n%s\n", $this->dumper->dump($this->dumpValue($definition->getMethodCalls()), 1, 12));
  112. }
  113. if (!$definition->isShared()) {
  114. $code .= " shared: false\n";
  115. }
  116. if (null !== $decoratedService = $definition->getDecoratedService()) {
  117. [$decorated, $renamedId, $priority] = $decoratedService;
  118. $code .= sprintf(" decorates: %s\n", $decorated);
  119. if (null !== $renamedId) {
  120. $code .= sprintf(" decoration_inner_name: %s\n", $renamedId);
  121. }
  122. if (0 !== $priority) {
  123. $code .= sprintf(" decoration_priority: %s\n", $priority);
  124. }
  125. $decorationOnInvalid = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  126. if (\in_array($decorationOnInvalid, [ContainerInterface::IGNORE_ON_INVALID_REFERENCE, ContainerInterface::NULL_ON_INVALID_REFERENCE])) {
  127. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE === $decorationOnInvalid ? 'null' : 'ignore';
  128. $code .= sprintf(" decoration_on_invalid: %s\n", $invalidBehavior);
  129. }
  130. }
  131. if ($callable = $definition->getFactory()) {
  132. $code .= sprintf(" factory: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0));
  133. }
  134. if ($callable = $definition->getConfigurator()) {
  135. $code .= sprintf(" configurator: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0));
  136. }
  137. return $code;
  138. }
  139. private function addServiceAlias(string $alias, Alias $id): string
  140. {
  141. $deprecated = '';
  142. if ($id->isDeprecated()) {
  143. $deprecated = " deprecated:\n";
  144. foreach ($id->getDeprecation('%alias_id%') as $key => $value) {
  145. if ('' !== $value) {
  146. $deprecated .= sprintf(" %s: %s\n", $key, $value);
  147. }
  148. }
  149. }
  150. if (!$id->isDeprecated() && $id->isPrivate()) {
  151. return sprintf(" %s: '@%s'\n", $alias, $id);
  152. }
  153. if ($id->isPublic()) {
  154. $deprecated = " public: true\n".$deprecated;
  155. }
  156. return sprintf(" %s:\n alias: %s\n%s", $alias, $id, $deprecated);
  157. }
  158. private function addServices(): string
  159. {
  160. if (!$this->container->getDefinitions()) {
  161. return '';
  162. }
  163. $code = "services:\n";
  164. foreach ($this->container->getDefinitions() as $id => $definition) {
  165. $code .= $this->addService($id, $definition);
  166. }
  167. $aliases = $this->container->getAliases();
  168. foreach ($aliases as $alias => $id) {
  169. while (isset($aliases[(string) $id])) {
  170. $id = $aliases[(string) $id];
  171. }
  172. $code .= $this->addServiceAlias($alias, $id);
  173. }
  174. return $code;
  175. }
  176. private function addParameters(): string
  177. {
  178. if (!$this->container->getParameterBag()->all()) {
  179. return '';
  180. }
  181. $parameters = $this->prepareParameters($this->container->getParameterBag()->all(), $this->container->isCompiled());
  182. return $this->dumper->dump(['parameters' => $parameters], 2);
  183. }
  184. /**
  185. * Dumps callable to YAML format.
  186. *
  187. * @param mixed $callable
  188. *
  189. * @return mixed
  190. */
  191. private function dumpCallable($callable)
  192. {
  193. if (\is_array($callable)) {
  194. if ($callable[0] instanceof Reference) {
  195. $callable = [$this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]];
  196. } else {
  197. $callable = [$callable[0], $callable[1]];
  198. }
  199. }
  200. return $callable;
  201. }
  202. /**
  203. * Dumps the value to YAML format.
  204. *
  205. * @return mixed
  206. *
  207. * @throws RuntimeException When trying to dump object or resource
  208. */
  209. private function dumpValue($value)
  210. {
  211. if ($value instanceof ServiceClosureArgument) {
  212. $value = $value->getValues()[0];
  213. }
  214. if ($value instanceof ArgumentInterface) {
  215. $tag = $value;
  216. if ($value instanceof TaggedIteratorArgument || ($value instanceof ServiceLocatorArgument && $tag = $value->getTaggedIteratorArgument())) {
  217. if (null === $tag->getIndexAttribute()) {
  218. $content = $tag->getTag();
  219. } else {
  220. $content = [
  221. 'tag' => $tag->getTag(),
  222. 'index_by' => $tag->getIndexAttribute(),
  223. ];
  224. if (null !== $tag->getDefaultIndexMethod()) {
  225. $content['default_index_method'] = $tag->getDefaultIndexMethod();
  226. }
  227. if (null !== $tag->getDefaultPriorityMethod()) {
  228. $content['default_priority_method'] = $tag->getDefaultPriorityMethod();
  229. }
  230. }
  231. return new TaggedValue($value instanceof TaggedIteratorArgument ? 'tagged_iterator' : 'tagged_locator', $content);
  232. }
  233. if ($value instanceof IteratorArgument) {
  234. $tag = 'iterator';
  235. } elseif ($value instanceof ServiceLocatorArgument) {
  236. $tag = 'service_locator';
  237. } else {
  238. throw new RuntimeException(sprintf('Unspecified Yaml tag for type "%s".', get_debug_type($value)));
  239. }
  240. return new TaggedValue($tag, $this->dumpValue($value->getValues()));
  241. }
  242. if (\is_array($value)) {
  243. $code = [];
  244. foreach ($value as $k => $v) {
  245. $code[$k] = $this->dumpValue($v);
  246. }
  247. return $code;
  248. } elseif ($value instanceof Reference) {
  249. return $this->getServiceCall((string) $value, $value);
  250. } elseif ($value instanceof Parameter) {
  251. return $this->getParameterCall((string) $value);
  252. } elseif ($value instanceof Expression) {
  253. return $this->getExpressionCall((string) $value);
  254. } elseif ($value instanceof Definition) {
  255. return new TaggedValue('service', (new Parser())->parse("_:\n".$this->addService('_', $value), Yaml::PARSE_CUSTOM_TAGS)['_']['_']);
  256. } elseif ($value instanceof AbstractArgument) {
  257. return new TaggedValue('abstract', $value->getText());
  258. } elseif (\is_object($value) || \is_resource($value)) {
  259. throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
  260. }
  261. return $value;
  262. }
  263. private function getServiceCall(string $id, Reference $reference = null): string
  264. {
  265. if (null !== $reference) {
  266. switch ($reference->getInvalidBehavior()) {
  267. case ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE: break;
  268. case ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE: break;
  269. case ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE: return sprintf('@!%s', $id);
  270. default: return sprintf('@?%s', $id);
  271. }
  272. }
  273. return sprintf('@%s', $id);
  274. }
  275. private function getParameterCall(string $id): string
  276. {
  277. return sprintf('%%%s%%', $id);
  278. }
  279. private function getExpressionCall(string $expression): string
  280. {
  281. return sprintf('@=%s', $expression);
  282. }
  283. private function prepareParameters(array $parameters, bool $escape = true): array
  284. {
  285. $filtered = [];
  286. foreach ($parameters as $key => $value) {
  287. if (\is_array($value)) {
  288. $value = $this->prepareParameters($value, $escape);
  289. } elseif ($value instanceof Reference || \is_string($value) && 0 === strpos($value, '@')) {
  290. $value = '@'.$value;
  291. }
  292. $filtered[$key] = $value;
  293. }
  294. return $escape ? $this->escape($filtered) : $filtered;
  295. }
  296. private function escape(array $arguments): array
  297. {
  298. $args = [];
  299. foreach ($arguments as $k => $v) {
  300. if (\is_array($v)) {
  301. $args[$k] = $this->escape($v);
  302. } elseif (\is_string($v)) {
  303. $args[$k] = str_replace('%', '%%', $v);
  304. } else {
  305. $args[$k] = $v;
  306. }
  307. }
  308. return $args;
  309. }
  310. }