-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ChainToggleStrategyFactory.php
69 lines (59 loc) · 2.12 KB
/
ChainToggleStrategyFactory.php
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
<?php
declare(strict_types=1);
namespace Pheature\Core\Toggle\Read;
use Pheature\Core\Toggle\Exception\InvalidStrategyTypeGiven;
use function array_map;
use function array_merge;
use function in_array;
/**
* @psalm-import-type WriteStrategy from \Pheature\Core\Toggle\Write\Strategy
*/
final class ChainToggleStrategyFactory implements ToggleStrategyFactory
{
private SegmentFactory $segmentFactory;
/** @var ToggleStrategyFactory[] */
private array $toggleStrategyFactories;
public function __construct(SegmentFactory $segmentFactory, ToggleStrategyFactory ...$toggleStrategyFactories)
{
$this->segmentFactory = $segmentFactory;
$this->toggleStrategyFactories = $toggleStrategyFactories;
}
/** @param WriteStrategy $strategy */
public function createFromArray(array $strategy): ToggleStrategy
{
return $this->create(
$strategy['strategy_id'],
$strategy['strategy_type'],
new Segments(...array_map(
function (array $segment): Segment {
return $this->segmentFactory->create(
$segment['segment_id'],
$segment['segment_type'],
$segment['criteria']
);
},
$strategy['segments']
))
);
}
public function create(string $strategyId, string $strategyType, ?Segments $segments = null): ToggleStrategy
{
foreach ($this->toggleStrategyFactories as $toggleStrategyFactory) {
if (in_array($strategyType, $toggleStrategyFactory->types(), true)) {
return $toggleStrategyFactory->create($strategyId, $strategyType, $segments);
}
}
throw InvalidStrategyTypeGiven::withType($strategyType);
}
public function types(): array
{
return array_unique(
array_merge(
...array_map(
static fn(ToggleStrategyFactory $strategyFactory) => $strategyFactory->types(),
$this->toggleStrategyFactories
)
)
);
}
}