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