Passed
Push — master ( a65ee9...c98373 )
by Nico
17:36 queued 07:37
created

StuRandom   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 80%

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 30
ccs 12
cts 15
cp 0.8
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A array_rand() 0 3 1
A generateRandomValueStandardNormalDistribution() 0 14 3
A rand() 0 7 2
1
<?php
2
3
namespace Stu\Module\Control;
4
5
/**
6
 * This class adds the possibility to inject a random generator
7
 */
8
class StuRandom
9
{
10 1
    public function rand(int $min, int $max, bool $useStandardNormalDistribution = false): int
11
    {
12 1
        if ($useStandardNormalDistribution) {
13 1
            return $this->generateRandomValueStandardNormalDistribution($min, $max);
14
        }
15
16
        return random_int($min, $max);
17
    }
18
19
    public function array_rand(array $array): string|int
20
    {
21
        return array_rand($array);
0 ignored issues
show
Bug Best Practice introduced by
The expression return array_rand($array) could return the type array which is incompatible with the type-hinted return integer|string. Consider adding an additional type-check to rule them out.
Loading history...
22
    }
23
24 1
    private function generateRandomValueStandardNormalDistribution(int $min, int $max): int
25
    {
26 1
        $mean = (int)(($min + $max) / 2); // MW
27 1
        $stdDeviation = (int) ($mean / 2.5); // FWHM
28
29
        do {
30 1
            $value = random_int($min, $max);
31 1
            $probability = exp(-0.5 * (($value - $mean) / $stdDeviation) ** 2); // normal distribution
32 1
            $randomProbability = random_int(0, mt_getrandmax()) / mt_getrandmax();
33
34 1
            if ($randomProbability <= $probability) {
35 1
                return $value;
36
            }
37 1
        } while (true);
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return integer. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
38
    }
39
}
40