-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTest.php
More file actions
135 lines (111 loc) · 2.51 KB
/
Copy pathTest.php
File metadata and controls
135 lines (111 loc) · 2.51 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
namespace Utopia\AB;
use Exception;
class Test
{
/**
* @var array
*/
protected static $results = [];
/**
* Get Result of All Tests
*
* @return array
*/
public static function results()
{
return self::$results;
}
/**
* Test Name
*
* @var string
*/
protected $name = '';
/**
* Test Variations
*
* @var array
*/
protected $variations = [];
/**
* Test Variations Probabilities
*
* @var array
*/
protected $probabilities = [];
/**
* Test constructor.
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* Add a New Variation to Test
*
* @param mixed $value
* @return $this
*/
public function variation(string $name, $value, int $probability = null): self
{
$this->variations[$name] = $value;
$this->probabilities[$name] = $probability;
return $this;
}
/**
* Run Test and Get Result
*
* @return mixed
*
* @throws Exception
*/
public function run()
{
$result = $this->chance();
$return = $this->variations[$result];
if (\is_callable($return)) {
$return = $return();
}
self::$results[$this->name] = $return;
return $return;
}
/**
* Get Random Variation Based on Probabilities Chance
*
*
* @throws Exception
*/
protected function chance(): string
{
$sum = 0;
$empty = 0;
foreach ($this->probabilities as $name => $value) {
$sum += $value;
if (empty($value)) {
$empty++;
}
}
if ($sum > 100) {
throw new Exception('Test Error: Total variation probabilities is bigger than 100%');
}
if ($sum < 100) { // Auto set probability when it has no value
foreach ($this->probabilities as $name => $value) {
if (empty($value)) {
$this->probabilities[$name] = (100 - $sum) / $empty;
}
}
}
$number = \rand(0, (int) \array_sum($this->probabilities) * 10);
$starter = 0;
$return = '';
foreach ($this->probabilities as $key => $val) {
$starter += $val * 10;
if ($number <= $starter) {
$return = $key;
break;
}
}
return $return;
}
}