ReferenceManager::isReference()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shapin\Datagen;
6
7
use Shapin\Datagen\Exception\DuplicateReferenceException;
8
use Shapin\Datagen\Exception\UnknownReferenceException;
9
10
class ReferenceManager
11
{
12
    private $references = [];
13
14
    public function add(string $fixture, string $name, $data): void
15
    {
16 8
        if (!isset($this->references[$fixture])) {
17
            $this->references[$fixture] = [];
18 8
        }
19 8
        if (isset($this->references[$fixture][$name])) {
20
            throw new DuplicateReferenceException($fixture, $name);
21 3
        }
22
23 3
        $this->references[$fixture][$name] = $data;
24 3
    }
25
26 3
    public function findAndReplace(array $data): array
27 1
    {
28
        $keys = array_keys($data);
29
        for ($i = 0; $i < \count($data); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
30 3
            $value = $data[$keys[$i]];
31 3
            if (\is_string($value) && $this->isReference($value)) {
32
                $data[$keys[$i]] = $this->resolveReference($value);
33
            }
34 3
            if (\is_array($value)) {
35 3
                $data[$keys[$i]] = $this->findAndReplace($value);
36
            }
37 6
        }
38
39 6
        return $data;
40 6
    }
41 6
42 6
    private function isReference(string $value): bool
43 2
    {
44
        return 'REF:' === substr($value, 0, 4);
45 5
    }
46 1
47
    private function resolveReference(string $value)
48
    {
49
        $parts = explode(':', $value);
50 5
51
        $accessors = explode('.', $parts[1]);
52
53 6
        $array = $this->references;
54
        foreach ($accessors as $accessor) {
55 6
            if (!isset($array[$accessor])) {
56
                throw new UnknownReferenceException("Unable to resolve Reference \"$value\".");
57
            }
58 2
59
            $array = $array[$accessor];
60 2
        }
61 2
62
        return $array;
63 2
    }
64
}
65