|
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) { |
|
|
|
|
|
|
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
|
|
|
|
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: