GraphvizDumper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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\Definition;
  13. use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
  14. use Symfony\Component\DependencyInjection\Reference;
  15. use Symfony\Component\DependencyInjection\Parameter;
  16. use Symfony\Component\DependencyInjection\ContainerBuilder;
  17. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  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. private $options = array(
  32. 'graph' => array('ratio' => 'compress'),
  33. 'node' => array('fontsize' => 11, 'fontname' => 'Arial', 'shape' => 'record'),
  34. 'edge' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => 0.5),
  35. 'node.instance' => array('fillcolor' => '#9999ff', 'style' => 'filled'),
  36. 'node.definition' => array('fillcolor' => '#eeeeee'),
  37. 'node.missing' => array('fillcolor' => '#ff9999', 'style' => 'filled'),
  38. );
  39. /**
  40. * Dumps the service container as a graphviz graph.
  41. *
  42. * Available options:
  43. *
  44. * * graph: The default options for the whole graph
  45. * * node: The default options for nodes
  46. * * edge: The default options for edges
  47. * * node.instance: The default options for services that are defined directly by object instances
  48. * * node.definition: The default options for services that are defined via service definition instances
  49. * * node.missing: The default options for missing services
  50. *
  51. * @return string The dot representation of the service container
  52. */
  53. public function dump(array $options = array())
  54. {
  55. foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) {
  56. if (isset($options[$key])) {
  57. $this->options[$key] = array_merge($this->options[$key], $options[$key]);
  58. }
  59. }
  60. $this->nodes = $this->findNodes();
  61. $this->edges = array();
  62. foreach ($this->container->getDefinitions() as $id => $definition) {
  63. $this->edges[$id] = array_merge(
  64. $this->findEdges($id, $definition->getArguments(), true, ''),
  65. $this->findEdges($id, $definition->getProperties(), false, '')
  66. );
  67. foreach ($definition->getMethodCalls() as $call) {
  68. $this->edges[$id] = array_merge(
  69. $this->edges[$id],
  70. $this->findEdges($id, $call[1], false, $call[0].'()')
  71. );
  72. }
  73. }
  74. return $this->container->resolveEnvPlaceholders($this->startDot().$this->addNodes().$this->addEdges().$this->endDot(), '__ENV_%s__');
  75. }
  76. /**
  77. * Returns all nodes.
  78. *
  79. * @return string A string representation of all nodes
  80. */
  81. private function addNodes()
  82. {
  83. $code = '';
  84. foreach ($this->nodes as $id => $node) {
  85. $aliases = $this->getAliases($id);
  86. $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']));
  87. }
  88. return $code;
  89. }
  90. /**
  91. * Returns all edges.
  92. *
  93. * @return string A string representation of all edges
  94. */
  95. private function addEdges()
  96. {
  97. $code = '';
  98. foreach ($this->edges as $id => $edges) {
  99. foreach ($edges as $edge) {
  100. $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"' : '');
  101. }
  102. }
  103. return $code;
  104. }
  105. /**
  106. * Finds all edges belonging to a specific service id.
  107. *
  108. * @param string $id The service id used to find edges
  109. * @param array $arguments An array of arguments
  110. * @param bool $required
  111. * @param string $name
  112. *
  113. * @return array An array of edges
  114. */
  115. private function findEdges($id, array $arguments, $required, $name, $lazy = false)
  116. {
  117. $edges = array();
  118. foreach ($arguments as $argument) {
  119. if ($argument instanceof Parameter) {
  120. $argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null;
  121. } elseif (is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) {
  122. $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null;
  123. }
  124. if ($argument instanceof Reference) {
  125. $lazyEdge = $lazy;
  126. if (!$this->container->has((string) $argument)) {
  127. $this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']);
  128. } elseif ('service_container' !== (string) $argument) {
  129. $lazyEdge = $lazy || $this->container->getDefinition((string) $argument)->isLazy();
  130. }
  131. $edges[] = array('name' => $name, 'required' => $required, 'to' => $argument, 'lazy' => $lazyEdge);
  132. } elseif ($argument instanceof ArgumentInterface) {
  133. $edges = array_merge($edges, $this->findEdges($id, $argument->getValues(), $required, $name, true));
  134. } elseif (is_array($argument)) {
  135. $edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name, $lazy));
  136. }
  137. }
  138. return $edges;
  139. }
  140. /**
  141. * Finds all nodes.
  142. *
  143. * @return array An array of all nodes
  144. */
  145. private function findNodes()
  146. {
  147. $nodes = array();
  148. $container = $this->cloneContainer();
  149. foreach ($container->getDefinitions() as $id => $definition) {
  150. $class = $definition->getClass();
  151. if ('\\' === substr($class, 0, 1)) {
  152. $class = substr($class, 1);
  153. }
  154. try {
  155. $class = $this->container->getParameterBag()->resolveValue($class);
  156. } catch (ParameterNotFoundException $e) {
  157. }
  158. $nodes[$id] = array('class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition'], array('style' => $definition->isShared() ? 'filled' : 'dotted')));
  159. $container->setDefinition($id, new Definition('stdClass'));
  160. }
  161. foreach ($container->getServiceIds() as $id) {
  162. if (array_key_exists($id, $container->getAliases())) {
  163. continue;
  164. }
  165. if (!$container->hasDefinition($id)) {
  166. $nodes[$id] = array('class' => str_replace('\\', '\\\\', get_class($container->get($id))), 'attributes' => $this->options['node.instance']);
  167. }
  168. }
  169. return $nodes;
  170. }
  171. private function cloneContainer()
  172. {
  173. $parameterBag = new ParameterBag($this->container->getParameterBag()->all());
  174. $container = new ContainerBuilder($parameterBag);
  175. $container->setDefinitions($this->container->getDefinitions());
  176. $container->setAliases($this->container->getAliases());
  177. $container->setResources($this->container->getResources());
  178. foreach ($this->container->getExtensions() as $extension) {
  179. $container->registerExtension($extension);
  180. }
  181. return $container;
  182. }
  183. /**
  184. * Returns the start dot.
  185. *
  186. * @return string The string representation of a start dot
  187. */
  188. private function startDot()
  189. {
  190. return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n",
  191. $this->addOptions($this->options['graph']),
  192. $this->addOptions($this->options['node']),
  193. $this->addOptions($this->options['edge'])
  194. );
  195. }
  196. /**
  197. * Returns the end dot.
  198. *
  199. * @return string
  200. */
  201. private function endDot()
  202. {
  203. return "}\n";
  204. }
  205. /**
  206. * Adds attributes.
  207. *
  208. * @param array $attributes An array of attributes
  209. *
  210. * @return string A comma separated list of attributes
  211. */
  212. private function addAttributes(array $attributes)
  213. {
  214. $code = array();
  215. foreach ($attributes as $k => $v) {
  216. $code[] = sprintf('%s="%s"', $k, $v);
  217. }
  218. return $code ? ', '.implode(', ', $code) : '';
  219. }
  220. /**
  221. * Adds options.
  222. *
  223. * @param array $options An array of options
  224. *
  225. * @return string A space separated list of options
  226. */
  227. private function addOptions(array $options)
  228. {
  229. $code = array();
  230. foreach ($options as $k => $v) {
  231. $code[] = sprintf('%s="%s"', $k, $v);
  232. }
  233. return implode(' ', $code);
  234. }
  235. /**
  236. * Dotizes an identifier.
  237. *
  238. * @param string $id The identifier to dotize
  239. *
  240. * @return string A dotized string
  241. */
  242. private function dotize($id)
  243. {
  244. return strtolower(preg_replace('/\W/i', '_', $id));
  245. }
  246. /**
  247. * Compiles an array of aliases for a specified service id.
  248. *
  249. * @param string $id A service id
  250. *
  251. * @return array An array of aliases
  252. */
  253. private function getAliases($id)
  254. {
  255. $aliases = array();
  256. foreach ($this->container->getAliases() as $alias => $origin) {
  257. if ($id == $origin) {
  258. $aliases[] = $alias;
  259. }
  260. }
  261. return $aliases;
  262. }
  263. }