Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
15 / 15 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
SecureRandomizer | |
100.00% |
15 / 15 |
|
100.00% |
5 / 5 |
7 | |
100.00% |
1 / 1 |
randomElements | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
randomElement | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
randomDigit | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
numberBetween | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
shuffle | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
2 |
1 | <?php |
2 | namespace Apie\Core\Randomizer; |
3 | |
4 | class SecureRandomizer implements RandomizerInterface |
5 | { |
6 | public function randomElements(array $elements, int $count): array |
7 | { |
8 | $res = []; |
9 | for ($i = 0; $i < $count; $i++) { |
10 | $res[] = $this->randomElement($elements); |
11 | } |
12 | return $res; |
13 | } |
14 | public function randomElement(array $elements): mixed |
15 | { |
16 | return $elements[random_int(0, count($elements) - 1)]; |
17 | } |
18 | public function randomDigit(): int |
19 | { |
20 | return random_int(0, 9); |
21 | } |
22 | public function numberBetween(int $minLength, int $maxLength): int |
23 | { |
24 | return random_int($minLength, $maxLength); |
25 | } |
26 | |
27 | public function shuffle(array& $list): void |
28 | { |
29 | $count = count($list); |
30 | // n log n is sufficient number of shuffles between 2 items |
31 | $numberOfShuffles = ($count * log10($count)); |
32 | for ($i = 0; $i < $numberOfShuffles; $i++) { |
33 | $left = random_int(0, $count - 1); |
34 | $right = random_int(0, $count - 1); |
35 | $tmp = $list[$left]; |
36 | $list[$left] = $list[$right]; |
37 | $list[$right] = $tmp; |
38 | } |
39 | } |
40 | } |