-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathMetricsBucket.php
executable file
·97 lines (80 loc) · 2.3 KB
/
MetricsBucket.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
<?php
namespace Unleash\Client\Metrics;
use DateTimeInterface;
use JetBrains\PhpStorm\ArrayShape;
use JsonSerializable;
use LogicException;
use Override;
/**
* @internal
*/
final class MetricsBucket implements JsonSerializable
{
/**
* @var array<MetricsBucketToggle>
*/
private array $toggles = [];
public function __construct(
private readonly DateTimeInterface $startDate,
private ?DateTimeInterface $endDate = null,
) {
}
public function addToggle(MetricsBucketToggle $toggle): self
{
$this->toggles[] = $toggle;
return $this;
}
public function getStartDate(): DateTimeInterface
{
return $this->startDate;
}
public function setEndDate(?DateTimeInterface $endDate): MetricsBucket
{
$this->endDate = $endDate;
return $this;
}
public function getEndDate(): ?DateTimeInterface
{
return $this->endDate;
}
/**
* @return array<MetricsBucketToggle>
*/
public function getToggles(): array
{
return $this->toggles;
}
/**
* @return array<string,mixed>
*/
#[ArrayShape(['start' => 'string', 'stop' => 'string', 'toggles' => 'array'])]
#[Override]
public function jsonSerialize(): array
{
$togglesArray = [];
if ($this->endDate === null) {
throw new LogicException('Cannot serialize incomplete bucket');
}
foreach ($this->toggles as $toggle) {
$featureName = $toggle->getFeature()->getName();
if (!isset($togglesArray[$featureName])) {
$togglesArray[$featureName] = [
'yes' => 0,
'no' => 0,
];
}
$updateField = $toggle->isSuccess() ? 'yes' : 'no';
++$togglesArray[$featureName][$updateField];
if ($toggle->getVariant() !== null) {
$variant = $toggle->getVariant();
$togglesArray[$featureName]['variants'][$variant->getName()] ??= 0;
++$togglesArray[$featureName]['variants'][$variant->getName()];
}
}
return [
'start' => $this->startDate->format('c'),
'stop' => $this->endDate->format('c'),
'toggles' => $togglesArray,
];
}
}