-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Feature.php
106 lines (88 loc) · 2.34 KB
/
Feature.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
<?php
declare(strict_types=1);
namespace Pheature\Core\Toggle\Write;
use Pheature\Core\Toggle\Write\Event\FeatureWasCreated;
use JsonSerializable;
use function array_map;
use function array_values;
final class Feature implements JsonSerializable
{
private FeatureId $featureId;
private bool $enabled;
/** @var Strategy[] */
private array $strategies = [];
/** @var array<object> */
private array $events = [];
/**
* Feature constructor.
*
* @param FeatureId $featureId
* @param bool $enabled
* @param Strategy[] $strategies
*/
public function __construct(FeatureId $featureId, bool $enabled, array $strategies = [])
{
$this->featureId = $featureId;
$this->enabled = $enabled;
foreach ($strategies as $strategy) {
$this->strategies[$strategy->id()->value()] = $strategy;
}
}
/**
* @return object[]
*/
public function release(): array
{
$events = $this->events;
$this->events = [];
return $events;
}
public static function withId(FeatureId $featureId): self
{
$feature = new self($featureId, false);
$feature->events[] = FeatureWasCreated::occur($featureId->value());
return $feature;
}
public function setStrategy(Strategy $strategy): void
{
$this->strategies[$strategy->id()->value()] = $strategy;
}
public function removeStrategy(StrategyId $strategyId): void
{
unset($this->strategies[$strategyId->value()]);
}
public function enable(): void
{
$this->enabled = true;
}
public function disable(): void
{
$this->enabled = false;
}
public function isEnabled(): bool
{
return $this->enabled;
}
public function id(): string
{
return $this->featureId->value();
}
/**
* @return Strategy[]
*/
public function strategies(): array
{
return array_values($this->strategies);
}
/**
* @return array<string, mixed>
*/
public function jsonSerialize(): array
{
return [
'feature_id' => $this->featureId->value(),
'enabled' => $this->enabled,
'strategies' => array_map(static fn(Strategy $strategy) => $strategy->jsonSerialize(), $this->strategies),
];
}
}