GraphvizDumper.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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\Argument\ArgumentInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Definition;
  14. use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
  15. use Symfony\Component\DependencyInjection\Parameter;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  17. use Symfony\Component\DependencyInjection\Reference;
  18. /**
  19. * GraphvizDumper dumps a service container as a graphviz file.
  20. *
  21. * You can convert the generated dot file with the dot utility (http://www.graphviz.org/):
  22. *
  23. * dot -Tpng container.dot > foo.png
  24. *
  25. * @author Fabien Potencier <fabien@symfony.com>
  26. */
  27. class GraphvizDumper extends Dumper
  28. {
  29. private $nodes;
  30. private $edges;
  31. // All values should be strings
  32. private $options = [
  33. 'graph' => ['ratio' => 'compress'],
  34. 'node' => ['fontsize' => '11', 'fontname' => 'Arial', 'shape' => 'record'],
  35. 'edge' => ['fontsize' => '9', 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => '0.5'],
  36. 'node.instance' => ['fillcolor' => '#9999ff', 'style' => 'filled'],
  37. 'node.definition' => ['fillcolor' => '#eeeeee'],
  38. 'node.missing' => ['fillcolor' => '#ff9999', 'style' => 'filled'],
  39. ];
  40. /**
  41. * Dumps the service container as a graphviz graph.
  42. *
  43. * Available options:
  44. *
  45. * * graph: The default options for the whole graph
  46. * * node: The default options for nodes
  47. * * edge: The default options for edges
  48. * * node.instance: The default options for services that are defined directly by object instances
  49. * * node.definition: The default options for services that are defined via service definition instances
  50. * * node.missing: The default options for missing services
  51. *
  52. * @return string The dot representation of the service container
  53. */
  54. public function dump(array $options = [])
  55. {
  56. foreach (['graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing'] as $key) {
  57. if (isset($options[$key])) {
  58. $this->options[$key] = array_merge($this->options[$key], $options[$key]);
  59. }
  60. }
  61. $this->nodes = $this->findNodes();
  62. $this->edges = [];
  63. foreach ($this->container->getDefinitions() as $id => $definition) {
  64. $this->edges[$id] = array_merge(
  65. $this->findEdges($id, $definition->getArguments(), true, ''),
  66. $this->findEdges($id, $definition->getProperties(), false, '')
  67. );
  68. foreach ($definition->getMethodCalls() as $call) {
  69. $this->edges[$id] = array_merge(
  70. $this->edges[$id],
  71. $this->findEdges($id, $call[1], false, $call[0].'()')
  72. );
  73. }
  74. }
  75. return $this->container->resolveEnvPlaceholders($this->startDot().$this->addNodes().$this->addEdges().$this->endDot(), '__ENV_%s__');
  76. }
  77. private function addNodes(): string
  78. {
  79. $code = '';
  80. foreach ($this->nodes as $id => $node) {
  81. $aliases = $this->getAliases($id);
  82. $code .= sprintf(" node_%s [label=\"%s\\n%s\\n\", shape=%s%s];\n", $this->dotize($id), $id.($aliases ? ' ('.implode(', ', $aliases).')' : ''), $node['class'], $this->options['node']['shape'], $this->addAttributes($node['attributes']));
  83. }
  84. return $code;
  85. }
  86. private function addEdges(): string
  87. {
  88. $code = '';
  89. foreach ($this->edges as $id => $edges) {
  90. foreach ($edges as $edge) {
  91. $code .= sprintf(" node_%s -> node_%s [label=\"%s\" style=\"%s\"%s];\n", $this->dotize($id), $this->dotize($edge['to']), $edge['name'], $edge['required'] ? 'filled' : 'dashed', $edge['lazy'] ? ' color="#9999ff"' : '');
  92. }
  93. }
  94. return $code;
  95. }
  96. /**
  97. * Finds all edges belonging to a specific service id.
  98. */
  99. private function findEdges(string $id, array $arguments, bool $required, string $name, bool $lazy = false): array
  100. {
  101. $edges = [];
  102. foreach ($arguments as $argument) {
  103. if ($argument instanceof Parameter) {
  104. $argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null;
  105. } elseif (\is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) {
  106. $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null;
  107. }
  108. if ($argument instanceof Reference) {
  109. $lazyEdge = $lazy;
  110. if (!$this->container->has((string) $argument)) {
  111. $this->nodes[(string) $argument] = ['name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']];
  112. } elseif ('service_container' !== (string) $argument) {
  113. $lazyEdge = $lazy || $this->container->getDefinition((string) $argument)->isLazy();
  114. }
  115. $edges[] = ['name' => $name, 'required' => $required, 'to' => $argument, 'lazy' => $lazyEdge];
  116. } elseif ($argument instanceof ArgumentInterface) {
  117. $edges = array_merge($edges, $this->findEdges($id, $argument->getValues(), $required, $name, true));
  118. } elseif ($argument instanceof Definition) {
  119. $edges = array_merge($edges,
  120. $this->findEdges($id, $argument->getArguments(), $required, ''),
  121. $this->findEdges($id, $argument->getProperties(), false, '')
  122. );
  123. foreach ($argument->getMethodCalls() as $call) {
  124. $edges = array_merge($edges, $this->findEdges($id, $call[1], false, $call[0].'()'));
  125. }
  126. } elseif (\is_array($argument)) {
  127. $edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name, $lazy));
  128. }
  129. }
  130. return $edges;
  131. }
  132. private function findNodes(): array
  133. {
  134. $nodes = [];
  135. $container = $this->cloneContainer();
  136. foreach ($container->getDefinitions() as $id => $definition) {
  137. $class = $definition->getClass();
  138. if ('\\' === substr($class, 0, 1)) {
  139. $class = substr($class, 1);
  140. }
  141. try {
  142. $class = $this->container->getParameterBag()->resolveValue($class);
  143. } catch (ParameterNotFoundException $e) {
  144. }
  145. $nodes[$id] = ['class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition'], ['style' => $definition->isShared() ? 'filled' : 'dotted'])];
  146. $container->setDefinition($id, new Definition('stdClass'));
  147. }
  148. foreach ($container->getServiceIds() as $id) {
  149. if (\array_key_exists($id, $container->getAliases())) {
  150. continue;
  151. }
  152. if (!$container->hasDefinition($id)) {
  153. $nodes[$id] = ['class' => str_replace('\\', '\\\\', \get_class($container->get($id))), 'attributes' => $this->options['node.instance']];
  154. }
  155. }
  156. return $nodes;
  157. }
  158. private function cloneContainer(): ContainerBuilder
  159. {
  160. $parameterBag = new ParameterBag($this->container->getParameterBag()->all());
  161. $container = new ContainerBuilder($parameterBag);
  162. $container->setDefinitions($this->container->getDefinitions());
  163. $container->setAliases($this->container->getAliases());
  164. $container->setResources($this->container->getResources());
  165. foreach ($this->container->getExtensions() as $extension) {
  166. $container->registerExtension($extension);
  167. }
  168. return $container;
  169. }
  170. private function startDot(): string
  171. {
  172. return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n",
  173. $this->addOptions($this->options['graph']),
  174. $this->addOptions($this->options['node']),
  175. $this->addOptions($this->options['edge'])
  176. );
  177. }
  178. private function endDot(): string
  179. {
  180. return "}\n";
  181. }
  182. private function addAttributes(array $attributes): string
  183. {
  184. $code = [];
  185. foreach ($attributes as $k => $v) {
  186. $code[] = sprintf('%s="%s"', $k, $v);
  187. }
  188. return $code ? ', '.implode(', ', $code) : '';
  189. }
  190. private function addOptions(array $options): string
  191. {
  192. $code = [];
  193. foreach ($options as $k => $v) {
  194. $code[] = sprintf('%s="%s"', $k, $v);
  195. }
  196. return implode(' ', $code);
  197. }
  198. private function dotize(string $id): string
  199. {
  200. return preg_replace('/\W/i', '_', $id);
  201. }
  202. private function getAliases(string $id): array
  203. {
  204. $aliases = [];
  205. foreach ($this->container->getAliases() as $alias => $origin) {
  206. if ($id == $origin) {
  207. $aliases[] = $alias;
  208. }
  209. }
  210. return $aliases;
  211. }
  212. }