-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVariationsTreeBuilder.php
More file actions
109 lines (93 loc) · 2.8 KB
/
VariationsTreeBuilder.php
File metadata and controls
109 lines (93 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare (strict_types=1);
namespace Coshi\Variator;
use Coshi\Variator\Variation\AbstractVariation;
use Coshi\Variator\Exception\Helper;
use Coshi\Variator\Variation\VariationInterface;
class VariationsTreeBuilder
{
public function __construct(VariationFactory $factory)
{
$this->factory = $factory;
}
/**
* @param array $config
*
* @return VariationInterface
*
* @throws Exception\CircularDependencyException
* @throws \InvalidArgumentException
*/
public function build(array $config)
{
/** @var AbstractVariation[] $variations */
$variations = [];
foreach ($config as $name => $variation) {
$variations[$name] = $this->factory->createNew($name, $variation);
}
return new ContainerVariation($this->buildTree($variations));
}
/**
* @param AbstractVariation[] $variations
*
* @return AbstractVariation[]
*
* @throws Exception\CircularDependencyException
*/
private function buildTree(array $variations)
{
$this->detectCircularDependencies($variations);
$dependent = [];
foreach ($variations as $root) {
foreach ($variations as $key => $nested) {
if ($nested->dependsOn($root->getName())) {
$dependent[] = $key;
$root->addNested($nested);
}
}
}
foreach ($dependent as $key) {
unset($variations[$key]);
}
return $variations;
}
/**
* @param array $variations
*
* @return array
*
* @throws Exception\CircularDependencyException
*/
private function detectCircularDependencies(array $variations)
{
$tree = [];
foreach ($variations as $variation) {
$tree[$variation->getName()] = $this->detectCircular($variations, $variation, [$variation->getName()]);
}
return $tree;
}
/**
* @param array $variations
* @param AbstractVariation $variation
* @param array $path
*
* @return bool
*
* @throws Exception\CircularDependencyException
*/
private function detectCircular(array $variations, AbstractVariation $variation, array $path)
{
foreach ($variations as $item) {
if ($item->dependsOn($variation->getName())) {
if ($item === $variation
|| $variation->dependsOn($item->getName())
|| in_array($item->getName(), $path, true)) {
$path[] = $item->getName();
throw Helper::fromPath(implode('.', $path));
}
$this->detectCircular($variations, $item, $path);
}
}
return false;
}
}