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