-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Unleash.php
118 lines (91 loc) Β· 2.98 KB
/
Unleash.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
namespace MikeFrancis\LaravelUnleash;
use function GuzzleHttp\json_decode;
use GuzzleHttp\ClientInterface;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use MikeFrancis\LaravelUnleash\Strategies\Contracts\Strategy;
class Unleash
{
private $client;
private $cache;
private $config;
private $request;
private $features = [];
public function __construct(ClientInterface $client, Cache $cache, Config $config, Request $request)
{
$this->client = $client;
$this->cache = $cache;
$this->config = $config;
$this->request = $request;
if (!$this->config->get('unleash.isEnabled')) {
return;
}
if ($this->config->get('unleash.cache.isEnabled')) {
$this->features = $this->cache->remember(
'unleash',
$this->config->get('unleash.cache.ttl'),
function () {
return $this->fetchFeatures();
}
);
} else {
$this->features = $this->fetchFeatures();
}
}
public function getFeatures(): array
{
return $this->features;
}
public function getFeature(string $name)
{
$features = $this->getFeatures();
return Arr::first(
$features,
function (array $unleashFeature) use ($name) {
return $name === $unleashFeature['name'];
}
);
}
public function isFeatureEnabled(string $name): bool
{
$feature = $this->getFeature($name);
$isEnabled = Arr::get($feature, 'enabled', false);
if (!$isEnabled) {
return false;
}
$strategies = Arr::get($feature, 'strategies', []);
$allStrategies = $this->config->get('unleash.strategies', []);
foreach ($strategies as $strategyData) {
$className = $strategyData['name'];
if (!array_key_exists($className, $allStrategies)) {
return false;
}
$strategy = new $allStrategies[$className];
if (!$strategy instanceof Strategy) {
throw new \Exception("${$className} does not implement base Strategy.");
}
$params = Arr::get($strategyData, 'parameters', []);
if (!$strategy->isEnabled($params, $this->request)) {
return false;
}
}
return $isEnabled;
}
public function isFeatureDisabled(string $name): bool
{
return !$this->isFeatureEnabled($name);
}
private function fetchFeatures(): array
{
try {
$response = $this->client->get('/api/client/features');
$data = json_decode((string) $response->getBody(), true);
return Arr::get($data, 'features', []);
} catch (\InvalidArgumentException $e) {
return [];
}
}
}