UniqueStrategy   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 13
dl 0
loc 46
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A generate() 0 21 4
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace DummyGenerator\Strategy;
6
7
class UniqueStrategy implements StrategyInterface
8
{
9
    /**
10
     * Contains all previously generated values, keyed by the Extension's function name.
11
     *
12
     * @var array<string, array<string, null>>
13
     */
14
    private array $previous = [];
15
16
    /**
17
     * With the unique generator you are guaranteed to never get the same two
18
     * values.
19
     *
20
     * <code>
21
     * // will never return twice the same value
22
     * $generator->randomElement(array(1, 2, 3));
23
     * </code>
24
     *
25
     * @param int $retries Maximum number of retries to find a unique value,
26
     *                         After which an OverflowException is thrown.
27
     */
28 3
    public function __construct(private readonly int $retries)
29
    {
30 3
    }
31
32 2
    public function generate(string $name, callable $callback): mixed
33
    {
34 2
        if (!isset($this->previous[$name])) {
35 2
            $this->previous[$name] = [];
36
        }
37
38 2
        $tries = 0;
39
40
        do {
41 2
            $response = $callback();
42
43 2
            ++$tries;
44
45 2
            if ($tries > $this->retries) {
46 1
                throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a unique value', $this->retries));
47
            }
48 2
        } while (array_key_exists(serialize($response), $this->previous[$name]));
49
50 2
        $this->previous[$name][serialize($response)] = null;
51
52 2
        return $response;
53
    }
54
}
55