-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathUnleashTwigExtension.php
93 lines (80 loc) · 2.2 KB
/
UnleashTwigExtension.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
<?php
namespace Unleash\Client\Bundle\Twig;
use JetBrains\PhpStorm\Pure;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
use Unleash\Client\Configuration\Context;
use Unleash\Client\DTO\Variant;
use Unleash\Client\Unleash;
final class UnleashTwigExtension extends AbstractExtension
{
public function __construct(
private readonly Unleash $unleash,
private readonly bool $functionsEnabled,
private readonly bool $filtersEnabled,
private readonly bool $testsEnabled,
private readonly bool $tagsEnabled,
) {
}
/**
* @return array<TwigFunction>
*/
public function getFunctions(): array
{
if (!$this->functionsEnabled) {
return [];
}
return [
new TwigFunction('feature_is_enabled', [$this, 'isEnabled']),
new TwigFunction('feature_variant', [$this, 'getVariant']),
];
}
/**
* @return array<TwigFilter>
*/
public function getFilters(): array
{
if (!$this->filtersEnabled) {
return [];
}
return [
new TwigFilter('feature_is_enabled', [$this, 'isEnabled']),
new TwigFilter('feature_variant', [$this, 'getVariant']),
];
}
/**
* @return array<TwigTest>
*/
public function getTests(): array
{
if (!$this->testsEnabled) {
return [];
}
return [
new TwigTest('enabled', [$this, 'isEnabled']),
];
}
/**
* @return array<FeatureTagTokenParser>
*/
#[Pure]
public function getTokenParsers(): array
{
if (!$this->tagsEnabled) {
return [];
}
return [
new FeatureTagTokenParser(get_class($this)),
];
}
public function isEnabled(string $featureName, ?Context $context = null, bool $default = false): bool
{
return $this->unleash->isEnabled($featureName, $context, $default);
}
public function getVariant(string $featureName, ?Context $context = null, ?Variant $fallback = null): Variant
{
return $this->unleash->getVariant($featureName, $context, $fallback);
}
}