@@ 13-60 (lines=48) @@ | ||
10 | */ |
|
11 | namespace Rafrsr\LibArray2Object\Reader; |
|
12 | ||
13 | class ReflectionReader implements PropertyReaderInterface |
|
14 | { |
|
15 | protected $onlyPublicProperties; |
|
16 | ||
17 | /** |
|
18 | * @param bool $onlyPublicProperties ignore private or protected properties |
|
19 | */ |
|
20 | public function __construct($onlyPublicProperties = false) |
|
21 | { |
|
22 | $this->onlyPublicProperties = $onlyPublicProperties; |
|
23 | } |
|
24 | ||
25 | /** |
|
26 | * {@inheritdoc} |
|
27 | */ |
|
28 | public function isReadable($object, $propertyPath) |
|
29 | { |
|
30 | $classRef = new \ReflectionClass(get_class($object)); |
|
31 | ||
32 | if (!$classRef->hasProperty($propertyPath)) { |
|
33 | return false; |
|
34 | } |
|
35 | ||
36 | $property = $classRef->getProperty($propertyPath); |
|
37 | if ($this->onlyPublicProperties && !$property->isPublic()) { |
|
38 | return false; |
|
39 | } |
|
40 | ||
41 | return true; |
|
42 | } |
|
43 | ||
44 | /** |
|
45 | * {@inheritdoc} |
|
46 | */ |
|
47 | public function getValue($object, $propertyPath) |
|
48 | { |
|
49 | if ($this->isReadable($object, $propertyPath)) { |
|
50 | $property = new \ReflectionProperty(get_class($object), $propertyPath); |
|
51 | if (!$property->isPublic()) { |
|
52 | $property->setAccessible(true); |
|
53 | } |
|
54 | ||
55 | return $property->getValue($object); |
|
56 | } |
|
57 | ||
58 | return; |
|
59 | } |
|
60 | } |
|
61 |
@@ 16-61 (lines=46) @@ | ||
13 | /** |
|
14 | * Class ReflectionWriter. |
|
15 | */ |
|
16 | class ReflectionWriter implements PropertyWriterInterface |
|
17 | { |
|
18 | protected $onlyPublicProperties; |
|
19 | ||
20 | /** |
|
21 | * @param bool $onlyPublicProperties ignore private or protected properties |
|
22 | */ |
|
23 | public function __construct($onlyPublicProperties = false) |
|
24 | { |
|
25 | $this->onlyPublicProperties = $onlyPublicProperties; |
|
26 | } |
|
27 | ||
28 | /** |
|
29 | * {@inheritdoc} |
|
30 | */ |
|
31 | public function isWritable($object, $propertyPath) |
|
32 | { |
|
33 | $classRef = new \ReflectionClass(get_class($object)); |
|
34 | ||
35 | if (!$classRef->hasProperty($propertyPath)) { |
|
36 | return false; |
|
37 | } |
|
38 | ||
39 | $property = $classRef->getProperty($propertyPath); |
|
40 | if ($this->onlyPublicProperties && !$property->isPublic()) { |
|
41 | return false; |
|
42 | } |
|
43 | ||
44 | return true; |
|
45 | } |
|
46 | ||
47 | /** |
|
48 | * {@inheritdoc} |
|
49 | */ |
|
50 | public function setValue(&$object, $propertyPath, $value) |
|
51 | { |
|
52 | if ($this->isWritable($object, $propertyPath)) { |
|
53 | $property = new \ReflectionProperty(get_class($object), $propertyPath); |
|
54 | if (!$property->isPublic()) { |
|
55 | $property->setAccessible(true); |
|
56 | } |
|
57 | ||
58 | $property->setValue($object, $value); |
|
59 | } |
|
60 | } |
|
61 | } |
|
62 |