GraphvizDumper.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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\ContainerBuilder;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  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. use Symfony\Component\DependencyInjection\Scope;
  19. /**
  20. * GraphvizDumper dumps a service container as a graphviz file.
  21. *
  22. * You can convert the generated dot file with the dot utility (http://www.graphviz.org/):
  23. *
  24. * dot -Tpng container.dot > foo.png
  25. *
  26. * @author Fabien Potencier <fabien@symfony.com>
  27. */
  28. class GraphvizDumper extends Dumper
  29. {
  30. private $nodes;
  31. private $edges;
  32. private $options = array(
  33. 'graph' => array('ratio' => 'compress'),
  34. 'node' => array('fontsize' => 11, 'fontname' => 'Arial', 'shape' => 'record'),
  35. 'edge' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => 'grey', 'arrowhead' => 'open', 'arrowsize' => 0.5),
  36. 'node.instance' => array('fillcolor' => '#9999ff', 'style' => 'filled'),
  37. 'node.definition' => array('fillcolor' => '#eeeeee'),
  38. 'node.missing' => array('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 = 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 bool $required
  112. * @param string $name
  113. *
  114. * @return array An array of edges
  115. */
  116. private function findEdges($id, array $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. $class = $definition->getClass();
  147. if ('\\' === substr($class, 0, 1)) {
  148. $class = substr($class, 1);
  149. }
  150. try {
  151. $class = $this->container->getParameterBag()->resolveValue($class);
  152. } catch (ParameterNotFoundException $e) {
  153. }
  154. $nodes[$id] = array('class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition'], array('style' => $definition->isShared() && ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope(false) ? 'filled' : 'dotted')));
  155. $container->setDefinition($id, new Definition('stdClass'));
  156. }
  157. foreach ($container->getServiceIds() as $id) {
  158. $service = $container->get($id);
  159. if (array_key_exists($id, $container->getAliases())) {
  160. continue;
  161. }
  162. if (!$container->hasDefinition($id)) {
  163. $class = ('service_container' === $id) ? \get_class($this->container) : \get_class($service);
  164. $nodes[$id] = array('class' => str_replace('\\', '\\\\', $class), 'attributes' => $this->options['node.instance']);
  165. }
  166. }
  167. return $nodes;
  168. }
  169. private function cloneContainer()
  170. {
  171. $parameterBag = new ParameterBag($this->container->getParameterBag()->all());
  172. $container = new ContainerBuilder($parameterBag);
  173. $container->setDefinitions($this->container->getDefinitions());
  174. $container->setAliases($this->container->getAliases());
  175. $container->setResources($this->container->getResources());
  176. foreach ($this->container->getScopes(false) as $scope => $parentScope) {
  177. $container->addScope(new Scope($scope, $parentScope));
  178. }
  179. foreach ($this->container->getExtensions() as $extension) {
  180. $container->registerExtension($extension);
  181. }
  182. return $container;
  183. }
  184. /**
  185. * Returns the start dot.
  186. *
  187. * @return string The string representation of a start dot
  188. */
  189. private function startDot()
  190. {
  191. return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n",
  192. $this->addOptions($this->options['graph']),
  193. $this->addOptions($this->options['node']),
  194. $this->addOptions($this->options['edge'])
  195. );
  196. }
  197. /**
  198. * Returns the end dot.
  199. *
  200. * @return string
  201. */
  202. private function endDot()
  203. {
  204. return "}\n";
  205. }
  206. /**
  207. * Adds attributes.
  208. *
  209. * @param array $attributes An array of attributes
  210. *
  211. * @return string A comma separated list of attributes
  212. */
  213. private function addAttributes(array $attributes)
  214. {
  215. $code = array();
  216. foreach ($attributes as $k => $v) {
  217. $code[] = sprintf('%s="%s"', $k, $v);
  218. }
  219. return $code ? ', '.implode(', ', $code) : '';
  220. }
  221. /**
  222. * Adds options.
  223. *
  224. * @param array $options An array of options
  225. *
  226. * @return string A space separated list of options
  227. */
  228. private function addOptions(array $options)
  229. {
  230. $code = array();
  231. foreach ($options as $k => $v) {
  232. $code[] = sprintf('%s="%s"', $k, $v);
  233. }
  234. return implode(' ', $code);
  235. }
  236. /**
  237. * Dotizes an identifier.
  238. *
  239. * @param string $id The identifier to dotize
  240. *
  241. * @return string A dotized string
  242. */
  243. private function dotize($id)
  244. {
  245. return strtolower(preg_replace('/\W/i', '_', $id));
  246. }
  247. /**
  248. * Compiles an array of aliases for a specified service id.
  249. *
  250. * @param string $id A service id
  251. *
  252. * @return array An array of aliases
  253. */
  254. private function getAliases($id)
  255. {
  256. $aliases = array();
  257. foreach ($this->container->getAliases() as $alias => $origin) {
  258. if ($id == $origin) {
  259. $aliases[] = $alias;
  260. }
  261. }
  262. return $aliases;
  263. }
  264. }