4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\Compiler;
14 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
17 * This is a directed graph of your services.
19 * This information can be used by your compiler passes instead of collecting
20 * it themselves which improves performance quite a lot.
22 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
24 * @final since version 3.4
26 class ServiceReferenceGraph
29 * @var ServiceReferenceGraphNode[]
31 private $nodes = array();
34 * Checks if the graph has a specific node.
36 * @param string $id Id to check
40 public function hasNode($id)
42 return isset($this->nodes[$id]);
46 * Gets a node by identifier.
48 * @param string $id The id to retrieve
50 * @return ServiceReferenceGraphNode
52 * @throws InvalidArgumentException if no node matches the supplied identifier
54 public function getNode($id)
56 if (!isset($this->nodes[$id])) {
57 throw new InvalidArgumentException(sprintf('There is no node with id "%s".', $id));
60 return $this->nodes[$id];
66 * @return ServiceReferenceGraphNode[]
68 public function getNodes()
76 public function clear()
78 foreach ($this->nodes as $node) {
81 $this->nodes = array();
85 * Connects 2 nodes together in the Graph.
87 * @param string $sourceId
88 * @param mixed $sourceValue
89 * @param string $destId
90 * @param mixed $destValue
91 * @param string $reference
95 public function connect($sourceId, $sourceValue, $destId, $destValue = null, $reference = null/*, bool $lazy = false, bool $weak = false*/)
97 $lazy = \func_num_args() >= 6 ? func_get_arg(5) : false;
98 $weak = \func_num_args() >= 7 ? func_get_arg(6) : false;
100 if (null === $sourceId || null === $destId) {
104 $sourceNode = $this->createNode($sourceId, $sourceValue);
105 $destNode = $this->createNode($destId, $destValue);
106 $edge = new ServiceReferenceGraphEdge($sourceNode, $destNode, $reference, $lazy, $weak);
108 $sourceNode->addOutEdge($edge);
109 $destNode->addInEdge($edge);
113 * Creates a graph node.
116 * @param mixed $value
118 * @return ServiceReferenceGraphNode
120 private function createNode($id, $value)
122 if (isset($this->nodes[$id]) && $this->nodes[$id]->getValue() === $value) {
123 return $this->nodes[$id];
126 return $this->nodes[$id] = new ServiceReferenceGraphNode($id, $value);