GraphvizDumper.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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\Definition;
  12. use Symfony\Component\DependencyInjection\Reference;
  13. use Symfony\Component\DependencyInjection\Parameter;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. use Symfony\Component\DependencyInjection\ContainerBuilder;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  17. /**
  18. * GraphvizDumper dumps a service container as a graphviz file.
  19. *
  20. * You can convert the generated dot file with the dot utility (http://www.graphviz.org/):
  21. *
  22. * dot -Tpng container.dot > foo.png
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. */
  26. class GraphvizDumper extends Dumper
  27. {
  28. private $nodes;
  29. private $edges;
  30. private $options = array(
  31. 'graph' => array('ratio' => 'compress'),
  32. 'node' => array('fontsize' => 11, 'fontname' => 'Arial', 'shape' => 'record'),
  33. 'edge' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => 0.5),
  34. 'node.instance' => array('fillcolor' => '#9999ff', 'style' => 'filled'),
  35. 'node.definition' => array('fillcolor' => '#eeeeee'),
  36. 'node.missing' => array('fillcolor' => '#ff9999', 'style' => 'filled'),
  37. );
  38. /**
  39. * Dumps the service container as a graphviz graph.
  40. *
  41. * Available options:
  42. *
  43. * * graph: The default options for the whole graph
  44. * * node: The default options for nodes
  45. * * edge: The default options for edges
  46. * * node.instance: The default options for services that are defined directly by object instances
  47. * * node.definition: The default options for services that are defined via service definition instances
  48. * * node.missing: The default options for missing services
  49. *
  50. * @param array $options An array of options
  51. *
  52. * @return string The dot representation of the service container
  53. */
  54. public function dump(array $options = array())
  55. {
  56. foreach (array('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 = array();
  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->startDot().$this->addNodes().$this->addEdges().$this->endDot();
  76. }
  77. /**
  78. * Returns all nodes.
  79. *
  80. * @return string A string representation of all nodes
  81. */
  82. private function addNodes()
  83. {
  84. $code = '';
  85. foreach ($this->nodes as $id => $node) {
  86. $aliases = $this->getAliases($id);
  87. $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']));
  88. }
  89. return $code;
  90. }
  91. /**
  92. * Returns all edges.
  93. *
  94. * @return string A string representation of all edges
  95. */
  96. private function addEdges()
  97. {
  98. $code = '';
  99. foreach ($this->edges as $id => $edges) {
  100. foreach ($edges as $edge) {
  101. $code .= sprintf(" node_%s -> node_%s [label=\"%s\" style=\"%s\"];\n", $this->dotize($id), $this->dotize($edge['to']), $edge['name'], $edge['required'] ? 'filled' : 'dashed');
  102. }
  103. }
  104. return $code;
  105. }
  106. /**
  107. * Finds all edges belonging to a specific service id.
  108. *
  109. * @param string $id The service id used to find edges
  110. * @param array $arguments An array of arguments
  111. * @param Boolean $required
  112. * @param string $name
  113. *
  114. * @return array An array of edges
  115. */
  116. private function findEdges($id, $arguments, $required, $name)
  117. {
  118. $edges = array();
  119. foreach ($arguments as $argument) {
  120. if ($argument instanceof Parameter) {
  121. $argument = $this->container->hasParameter($argument) ? $this->container->getParameter($argument) : null;
  122. } elseif (is_string($argument) && preg_match('/^%([^%]+)%$/', $argument, $match)) {
  123. $argument = $this->container->hasParameter($match[1]) ? $this->container->getParameter($match[1]) : null;
  124. }
  125. if ($argument instanceof Reference) {
  126. if (!$this->container->has((string) $argument)) {
  127. $this->nodes[(string) $argument] = array('name' => $name, 'required' => $required, 'class' => '', 'attributes' => $this->options['node.missing']);
  128. }
  129. $edges[] = array('name' => $name, 'required' => $required, 'to' => $argument);
  130. } elseif (is_array($argument)) {
  131. $edges = array_merge($edges, $this->findEdges($id, $argument, $required, $name));
  132. }
  133. }
  134. return $edges;
  135. }
  136. /**
  137. * Finds all nodes.
  138. *
  139. * @return array An array of all nodes
  140. */
  141. private function findNodes()
  142. {
  143. $nodes = array();
  144. $container = $this->cloneContainer();
  145. foreach ($container->getDefinitions() as $id => $definition) {
  146. $nodes[$id] = array('class' => str_replace('\\', '\\\\', $this->container->getParameterBag()->resolveValue($definition->getClass())), 'attributes' => array_merge($this->options['node.definition'], array('style' => ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope() ? 'filled' : 'dotted')));
  147. $container->setDefinition($id, new Definition('stdClass'));
  148. }
  149. foreach ($container->getServiceIds() as $id) {
  150. $service = $container->get($id);
  151. if (in_array($id, array_keys($container->getAliases()))) {
  152. continue;
  153. }
  154. if (!$container->hasDefinition($id)) {
  155. $class = ('service_container' === $id) ? get_class($this->container) : get_class($service);
  156. $nodes[$id] = array('class' => str_replace('\\', '\\\\', $class), 'attributes' => $this->options['node.instance']);
  157. }
  158. }
  159. return $nodes;
  160. }
  161. private function cloneContainer()
  162. {
  163. $parameterBag = new ParameterBag($this->container->getParameterBag()->all());
  164. $container = new ContainerBuilder($parameterBag);
  165. $container->setDefinitions($this->container->getDefinitions());
  166. $container->setAliases($this->container->getAliases());
  167. $container->setResources($this->container->getResources());
  168. foreach ($this->container->getScopes() as $scope) {
  169. $container->addScope($scope);
  170. }
  171. foreach ($this->container->getExtensions() as $extension) {
  172. $container->registerExtension($extension);
  173. }
  174. return $container;
  175. }
  176. /**
  177. * Returns the start dot.
  178. *
  179. * @return string The string representation of a start dot
  180. */
  181. private function startDot()
  182. {
  183. return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n",
  184. $this->addOptions($this->options['graph']),
  185. $this->addOptions($this->options['node']),
  186. $this->addOptions($this->options['edge'])
  187. );
  188. }
  189. /**
  190. * Returns the end dot.
  191. *
  192. * @return string
  193. */
  194. private function endDot()
  195. {
  196. return "}\n";
  197. }
  198. /**
  199. * Adds attributes
  200. *
  201. * @param array $attributes An array of attributes
  202. *
  203. * @return string A comma separated list of attributes
  204. */
  205. private function addAttributes($attributes)
  206. {
  207. $code = array();
  208. foreach ($attributes as $k => $v) {
  209. $code[] = sprintf('%s="%s"', $k, $v);
  210. }
  211. return $code ? ', '.implode(', ', $code) : '';
  212. }
  213. /**
  214. * Adds options
  215. *
  216. * @param array $options An array of options
  217. *
  218. * @return string A space separated list of options
  219. */
  220. private function addOptions($options)
  221. {
  222. $code = array();
  223. foreach ($options as $k => $v) {
  224. $code[] = sprintf('%s="%s"', $k, $v);
  225. }
  226. return implode(' ', $code);
  227. }
  228. /**
  229. * Dotizes an identifier.
  230. *
  231. * @param string $id The identifier to dotize
  232. *
  233. * @return string A dotized string
  234. */
  235. private function dotize($id)
  236. {
  237. return strtolower(preg_replace('/[^\w]/i', '_', $id));
  238. }
  239. /**
  240. * Compiles an array of aliases for a specified service id.
  241. *
  242. * @param string $id A service id
  243. *
  244. * @return array An array of aliases
  245. */
  246. private function getAliases($id)
  247. {
  248. $aliases = array();
  249. foreach ($this->container->getAliases() as $alias => $origin) {
  250. if ($id == $origin) {
  251. $aliases[] = $alias;
  252. }
  253. }
  254. return $aliases;
  255. }
  256. }