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
|
4 |
|
public function __construct(string $property) |
21
|
|
|
{ |
22
|
4 |
|
$this->property = $property; |
23
|
4 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param object $object |
27
|
|
|
* @param mixed $value |
28
|
|
|
*/ |
29
|
2 |
View Code Duplication |
public function setValue($object, $value) |
|
|
|
|
30
|
|
|
{ |
31
|
2 |
|
if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) { |
32
|
|
|
$class = (new \ReflectionClass($object))->getParentClass()->name; |
33
|
|
|
} else { |
34
|
2 |
|
$class = get_class($object); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
try { |
38
|
2 |
|
$reflectionProperty = new \ReflectionProperty($class, $this->property); |
39
|
1 |
|
} catch (\ReflectionException $e) { |
40
|
1 |
|
throw DeserializerLogicException::createMissingProperty($class, $this->property); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
$reflectionProperty->setAccessible(true); |
44
|
1 |
|
$reflectionProperty->setValue($object, $value); |
45
|
1 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param object $object |
49
|
|
|
* |
50
|
|
|
* @return mixed |
51
|
|
|
*/ |
52
|
2 |
View Code Duplication |
public function getValue($object) |
|
|
|
|
53
|
|
|
{ |
54
|
2 |
|
if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) { |
55
|
|
|
$class = (new \ReflectionClass($object))->getParentClass()->name; |
56
|
|
|
} else { |
57
|
2 |
|
$class = get_class($object); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
try { |
61
|
2 |
|
$reflectionProperty = new \ReflectionProperty($class, $this->property); |
62
|
1 |
|
} catch (\ReflectionException $e) { |
63
|
1 |
|
throw DeserializerLogicException::createMissingProperty($class, $this->property); |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
$reflectionProperty->setAccessible(true); |
67
|
|
|
|
68
|
1 |
|
return $reflectionProperty->getValue($object); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
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.