-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathToggleRouter.php
96 lines (77 loc) · 2.87 KB
/
ToggleRouter.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
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
<?php
namespace Trompette\FeatureToggles;
use Assert\Assert;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\SyntaxError;
class ToggleRouter implements LoggerAwareInterface
{
use LoggerAwareTrait;
/** @var FeatureRegistry */
private $registry;
/** @var TogglingStrategy[] */
private $strategies;
public function __construct(FeatureRegistry $registry, array $strategies = [])
{
Assert::thatAll($strategies)->isInstanceOf(TogglingStrategy::class);
$this->registry = $registry;
$this->strategies = $strategies;
$this->setLogger(new NullLogger());
}
public function hasFeature(string $target, string $feature): bool
{
if (!$this->registry->exists($feature)) {
$this->logger->warning('Feature is unregistered', [
'target' => $target,
'feature' => $feature,
]);
return false;
}
$expression = $this->registry->getDefinition($feature)->getStrategy();
$values = array_map(
function (TogglingStrategy $strategy) use ($target, $feature) {
return $strategy->decideIfTargetHasFeature($target, $feature);
},
$this->strategies
);
try {
return (bool) (new ExpressionLanguage())->evaluate($expression, $values);
} catch (SyntaxError $error) {
$this->logger->warning('Feature strategy is invalid', [
'target' => $target,
'feature' => $feature,
'expression' => $expression,
'values' => $values,
'error' => $error->getMessage(),
]);
return false;
}
}
public function getFeatureConfiguration(string $feature): array
{
return array_map(
function (TogglingStrategy $strategy) use ($feature) {
return $strategy->getConfiguration($feature);
},
$this->strategies
);
}
public function configureFeature(string $feature, string $strategy, string $method, $parameters = []): void
{
Assert::that($this->strategies)->keyExists($strategy, "$strategy is an invalid strategy");
Assert::that($method)->methodExists($this->strategies[$strategy], "$method() is absent from strategy");
if (!is_array($parameters)) {
$parameters = [$parameters];
}
$parameters = array_merge($parameters, [$feature]);
$this->strategies[$strategy]->$method(...$parameters);
$this->logger->info('Feature has been configured', [
'feature' => $feature,
'strategy' => $strategy,
'method' => $method,
'parameters' => $parameters,
]);
}
}