1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Deserialization\Doctrine\Accessor; |
6
|
|
|
|
7
|
|
|
use Chubbyphp\Deserialization\Accessor\AccessorInterface; |
8
|
|
|
use Chubbyphp\Deserialization\DeserializerLogicException; |
9
|
|
|
use Doctrine\Common\Persistence\Proxy; |
10
|
|
|
|
11
|
|
|
final class PropertyAccessor implements AccessorInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
private $property; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param string $property |
20
|
|
|
*/ |
21
|
|
|
public function __construct(string $property) |
22
|
|
|
{ |
23
|
|
|
$this->property = $property; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param object $object |
28
|
|
|
* @param mixed $value |
29
|
|
|
*/ |
30
|
|
|
public function setValue($object, $value) |
31
|
|
|
{ |
32
|
|
|
$reflectionProperty = $this->getReflectionProperty($this->getClass($object)); |
33
|
|
|
$reflectionProperty->setAccessible(true); |
34
|
|
|
$reflectionProperty->setValue($object, $value); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param object $object |
39
|
|
|
* |
40
|
|
|
* @return mixed |
41
|
|
|
*/ |
42
|
|
|
public function getValue($object) |
43
|
|
|
{ |
44
|
|
|
$reflectionProperty = $this->getReflectionProperty($this->getClass($object)); |
45
|
|
|
$reflectionProperty->setAccessible(true); |
46
|
|
|
|
47
|
|
|
return $reflectionProperty->getValue($object); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param object $object |
52
|
|
|
* |
53
|
|
|
* @return string |
54
|
|
|
*/ |
55
|
|
|
private function getClass($object): string |
56
|
|
|
{ |
57
|
|
|
if ($object instanceof Proxy) { |
58
|
|
|
if (!$object->__isInitialized()) { |
59
|
|
|
$object->__load(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return (new \ReflectionClass($object))->getParentClass()->name; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return get_class($object); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param string $class |
70
|
|
|
* |
71
|
|
|
* @return \ReflectionProperty |
72
|
|
|
*/ |
73
|
|
View Code Duplication |
private function getReflectionProperty(string $class): \ReflectionProperty |
|
|
|
|
74
|
|
|
{ |
75
|
|
|
try { |
76
|
|
|
return new \ReflectionProperty($class, $this->property); |
77
|
|
|
} catch (\ReflectionException $e) { |
78
|
|
|
throw DeserializerLogicException::createMissingProperty($class, $this->property); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.