1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vox\Data; |
4
|
|
|
|
5
|
|
|
use Metadata\MetadataFactoryInterface; |
6
|
|
|
use RuntimeException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Accesses objects data through setters, getters and reflection |
10
|
|
|
* |
11
|
|
|
* @author Jhonatan Teixeira <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
class PropertyAccessor implements PropertyAccessorInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var MetadataFactoryInterface |
17
|
|
|
*/ |
18
|
|
|
private $metadataFactory; |
19
|
|
|
|
20
|
4 |
|
public function __construct(MetadataFactoryInterface $metadataFactory) |
21
|
|
|
{ |
22
|
4 |
|
$this->metadataFactory = $metadataFactory; |
23
|
4 |
|
} |
24
|
|
|
|
25
|
3 |
|
public function get($object, string $name) |
26
|
|
|
{ |
27
|
3 |
|
if (preg_match('/\./', $name)) { |
28
|
2 |
|
$properties = explode('.', $name); |
29
|
2 |
|
$name = array_pop($properties); |
30
|
|
|
|
31
|
2 |
|
foreach ($properties as $property) { |
32
|
2 |
|
$object = $this->get($object, $property); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
3 |
|
$metadata = $this->metadataFactory->getMetadataForClass(get_class($object)); |
37
|
|
|
|
38
|
3 |
|
$getterName = sprintf('get%s', ucfirst($name)); |
39
|
|
|
|
40
|
3 |
|
if (isset($metadata->methodMetadata[$getterName])) { |
|
|
|
|
41
|
3 |
|
return $metadata->methodMetadata[$getterName]->invoke($object); |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
if (!isset($metadata->propertyMetadata[$name])) { |
|
|
|
|
45
|
|
|
throw new RuntimeException("property $name doesn't exists on {$metadata->name}"); |
|
|
|
|
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
return $metadata->propertyMetadata[$name]->getValue($object); |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
public function set($object, string $name, $value) |
52
|
|
|
{ |
53
|
3 |
|
if (preg_match('/\./', $name)) { |
54
|
1 |
|
$properties = explode('.', $name); |
55
|
1 |
|
$name = array_pop($properties); |
56
|
|
|
|
57
|
1 |
|
foreach ($properties as $property) { |
58
|
1 |
|
$object = $this->get($object, $property); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
3 |
|
$metadata = $this->metadataFactory->getMetadataForClass(get_class($object)); |
63
|
|
|
|
64
|
3 |
|
$setterName = sprintf('set%s', ucfirst($name)); |
65
|
|
|
|
66
|
3 |
|
if (isset($metadata->methodMetadata[$setterName])) { |
|
|
|
|
67
|
1 |
|
$metadata->methodMetadata[$setterName]->invoke($object, [$value]); |
68
|
|
|
|
69
|
1 |
|
return; |
70
|
|
|
} |
71
|
|
|
|
72
|
3 |
|
if (!isset($metadata->propertyMetadata[$name])) { |
|
|
|
|
73
|
|
|
throw new RuntimeException("property $name doesn't exists on {$metadata->name}"); |
|
|
|
|
74
|
|
|
} |
75
|
|
|
|
76
|
3 |
|
$metadata->propertyMetadata[$name]->setValue($object, $value); |
77
|
3 |
|
} |
78
|
|
|
} |
79
|
|
|
|