Passed
Push — master ( a50590...b54c62 )
by Dominik
03:00
created

PropertyAccessor::getReflectionProperty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
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
    public function setValue($object, $value)
30
    {
31 3
        $reflectionProperty = $this->getReflectionProperty($this->getClass($object));
32 2
        $reflectionProperty->setAccessible(true);
33 2
        $reflectionProperty->setValue($object, $value);
34 2
    }
35
36
    /**
37
     * @param object $object
38
     *
39
     * @return mixed
40
     */
41 4
    public function getValue($object)
42
    {
43 4
        $reflectionProperty = $this->getReflectionProperty($this->getClass($object));
44 3
        $reflectionProperty->setAccessible(true);
45
46 3
        return $reflectionProperty->getValue($object);
47
    }
48
49
    /**
50
     * @param object $object
51
     *
52
     * @return string
53
     */
54 6
    private function getClass($object): string
55
    {
56 6
        if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) {
57 2
            return (new \ReflectionClass($object))->getParentClass()->name;
58
        }
59
60 4
        return get_class($object);
61
    }
62
63
    /**
64
     * @param string $class
65
     *
66
     * @return \ReflectionProperty
67
     */
68 6
    private function getReflectionProperty(string $class): \ReflectionProperty
69
    {
70
        try {
71 6
            return new \ReflectionProperty($class, $this->property);
72 2
        } catch (\ReflectionException $e) {
73 2
            throw DeserializerLogicException::createMissingProperty($class, $this->property);
74
        }
75
    }
76
}
77