|
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
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccess; |
|
10
|
|
|
|
|
11
|
|
|
class ReferenceManager |
|
12
|
|
|
{ |
|
13
|
|
|
private $references; |
|
14
|
|
|
|
|
15
|
10 |
|
public function __construct() |
|
16
|
|
|
{ |
|
17
|
10 |
|
$this->references = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); |
|
18
|
10 |
|
} |
|
19
|
|
|
|
|
20
|
5 |
|
public function add(string $fixture, string $name, array $data): void |
|
21
|
|
|
{ |
|
22
|
5 |
|
if (!array_key_exists($fixture, $this->references)) { |
|
23
|
5 |
|
$this->references[$fixture] = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); |
|
24
|
|
|
} |
|
25
|
5 |
|
if (array_key_exists($name, $this->references[$fixture])) { |
|
26
|
1 |
|
throw new DuplicateReferenceException($fixture, $name); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
5 |
|
if (!is_object($data)) { |
|
30
|
5 |
|
$data = new \ArrayObject($data, \ArrayObject::ARRAY_AS_PROPS); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
5 |
|
$this->references[$fixture][$name] = $data; |
|
34
|
5 |
|
} |
|
35
|
|
|
|
|
36
|
2 |
|
public function get(string $fixture, string $name) |
|
37
|
|
|
{ |
|
38
|
2 |
|
if (!isset($this->references[$fixture][$name])) { |
|
39
|
1 |
|
throw new UnknownReferenceException($fixture, $name); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
1 |
|
return $this->references[$fixture][$name]; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
6 |
|
public function findAndReplace(array $data): array |
|
46
|
|
|
{ |
|
47
|
6 |
|
$keys = array_keys($data); |
|
48
|
6 |
|
for ($i = 0; $i < count($data); ++$i) { |
|
|
|
|
|
|
49
|
6 |
|
$value = $data[$keys[$i]]; |
|
50
|
6 |
|
if (is_string($value) && $this->isReference($value)) { |
|
51
|
2 |
|
$data[$keys[$i]] = $this->resolveReference($value); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
5 |
|
return $data; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
6 |
|
private function isReference(string $value): bool |
|
59
|
|
|
{ |
|
60
|
6 |
|
return 'REF:' === substr($value, 0, 4); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
2 |
|
private function resolveReference(string $value) |
|
64
|
|
|
{ |
|
65
|
2 |
|
$propertyAccessor = PropertyAccess::createPropertyAccessor(); |
|
66
|
2 |
|
$parts = explode(':', $value); |
|
67
|
|
|
|
|
68
|
2 |
|
$ref = $parts[1]; |
|
69
|
|
|
|
|
70
|
2 |
|
return $propertyAccessor->getValue($this->references, $ref); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
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: