-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path04-custom-strategy.php
executable file
·79 lines (68 loc) · 2.93 KB
/
04-custom-strategy.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
<?php
/**
* Here we are creating a kill switch maintenance strategy which allows access from whitelisted IP addresses,
* this might be slightly more useful than the April Fools strategy from README.
*/
use Unleash\Client\Configuration\Context;
use Unleash\Client\DTO\DefaultStrategy;
use Unleash\Client\DTO\Strategy;
use Unleash\Client\Strategy\AbstractStrategyHandler;
use Unleash\Client\Strategy\IpAddressStrategyHandler;
use Unleash\Client\UnleashBuilder;
require __DIR__ . '/_common.php';
final class MaintenanceKillSwitchStrategyHandler extends AbstractStrategyHandler
{
/**
* Let's reuse the IP address strategy because whitelisting IPs is pretty much the opposite of that
*/
public function __construct(private IpAddressStrategyHandler $ipAddressStrategyHandler)
{
}
public function getStrategyName(): string
{
return 'killSwitch';
}
/**
* We could implement the logic ourselves or we can reuse the existing strategy and return the reverse.
*
* Note that if the kill switch toggle is disabled in Unleash it won't even get here and thus in this method
* we can always assume the toggle is enabled.
*/
public function isEnabled(Strategy $strategy, Context $context): bool
{
// assume we named our parameter with whitelisted IPs as ipAddresses
$whitelistIpAddresses = $this->findParameter('ipAddresses', $strategy);
if ($whitelistIpAddresses === null) {
// kill switch is the reverse of usual feature, meaning if no ip address is defined, assume the kill
// switch is active
return true;
}
/**
* Here we create a strategy DTO that will be passed to IpAddressStrategyHandler which expects the list of
* IPs in the "IPs" parameter. If you want this kill switch to ignore constraints, you can just not pass
* them to the transformed strategy
*/
$transformedStrategy = new DefaultStrategy(
$this->getStrategyName(),
[
'IPs' => $whitelistIpAddresses,
],
$strategy->getConstraints()
);
// here we return the reverse result of ip address strategy handler because we want any whitelisted ip address
// to return false meaning the kill switch is not enabled for them
return !$this->ipAddressStrategyHandler->isEnabled($transformedStrategy, $context);
}
}
$unleash = UnleashBuilder::create()
->withAppName($appName)
->withAppUrl($appUrl)
->withInstanceId($instanceId)
->withHeader('Authorization', $apiKey)
->withStrategy(new KillSwitchStrategyHandler(new IpAddressStrategyHandler())) // add our custom strategy
->build();
if ($unleash->isEnabled('myAppKillSwitch')) {
echo "Kill switch is enabled, exiting", PHP_EOL;
exit();
}
echo "Kill switch not enabled, cool!", PHP_EOL;