ChanceStrategy   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 9
dl 0
loc 27
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 4
A generate() 0 7 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace DummyGenerator\Strategy;
6
7
use DummyGenerator\Core\Randomizer\Randomizer;
8
use DummyGenerator\Definitions\Randomizer\RandomizerInterface;
9
10
class ChanceStrategy implements StrategyInterface
11
{
12
    private RandomizerInterface $randomizer;
13
14
    /**
15
     * Get a value only some percentage of the time.
16
     *
17
     * @param float $weight A probability between 0 and 1, 0 means that we always get the default value.
18
     */
19 2
    public function __construct(private readonly float $weight, ?RandomizerInterface $randomizer = null, private readonly mixed $default = null)
20
    {
21 2
        if ($randomizer === null) {
22 2
            $this->randomizer = new Randomizer();
23
        }
24
25 2
        if ($this->weight < 0 || $this->weight > 1) {
26 1
            throw new \InvalidArgumentException('Weight should be a float between 0 and 1');
27
        }
28
    }
29
30 1
    public function generate(string $name, callable $callback): mixed
31
    {
32 1
        if ($this->randomizer->getInt(1, 100) > (100 * $this->weight)) {
33 1
            return $this->default;
34
        }
35
36 1
        return $callback();
37
    }
38
}
39