1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Deserialization\Accessor; |
6
|
|
|
|
7
|
|
|
use Chubbyphp\Deserialization\DeserializerLogicException; |
8
|
|
|
use Doctrine\Common\Persistence\Proxy; |
9
|
|
|
|
10
|
|
|
final class PropertyAccessor implements AccessorInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
private $property; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param string $property |
19
|
|
|
*/ |
20
|
6 |
|
public function __construct(string $property) |
21
|
|
|
{ |
22
|
6 |
|
$this->property = $property; |
23
|
6 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param object $object |
27
|
|
|
* @param mixed $value |
28
|
|
|
*/ |
29
|
3 |
View Code Duplication |
public function setValue($object, $value) |
|
|
|
|
30
|
|
|
{ |
31
|
3 |
|
$class = $this->getClass($object); |
32
|
|
|
|
33
|
3 |
|
if (!property_exists($class, $this->property)) { |
34
|
1 |
|
throw DeserializerLogicException::createMissingProperty($class, $this->property); |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
$setter = \Closure::bind( |
38
|
2 |
|
function ($property, $value) { |
39
|
2 |
|
$this->$property = $value; |
40
|
2 |
|
}, |
41
|
2 |
|
$object, |
42
|
2 |
|
$class |
43
|
|
|
); |
44
|
|
|
|
45
|
2 |
|
return $setter($this->property, $value); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param object $object |
50
|
|
|
* |
51
|
|
|
* @return mixed |
52
|
|
|
*/ |
53
|
4 |
View Code Duplication |
public function getValue($object) |
|
|
|
|
54
|
|
|
{ |
55
|
4 |
|
$class = $this->getClass($object); |
56
|
|
|
|
57
|
4 |
|
if (!property_exists($class, $this->property)) { |
58
|
1 |
|
throw DeserializerLogicException::createMissingProperty($class, $this->property); |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
$getter = \Closure::bind( |
62
|
3 |
|
function ($property) { |
63
|
3 |
|
return $this->$property; |
64
|
3 |
|
}, |
65
|
3 |
|
$object, |
66
|
3 |
|
$class |
67
|
|
|
); |
68
|
|
|
|
69
|
3 |
|
return $getter($this->property); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param object $object |
74
|
|
|
* |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
6 |
|
private function getClass($object): string |
78
|
|
|
{ |
79
|
6 |
|
if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) { |
80
|
2 |
|
if (!$object->__isInitialized()) { |
81
|
2 |
|
$object->__load(); |
82
|
|
|
} |
83
|
|
|
|
84
|
2 |
|
return (new \ReflectionClass($object))->getParentClass()->name; |
85
|
|
|
} |
86
|
|
|
|
87
|
4 |
|
return get_class($object); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|
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.