YamlDumper.php 12 KB

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