ChanceStrategy::generate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 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