Passed
Pull Request — master (#11)
by Dominik
04:20 queued 01:29
created

PropertyAccessor::getClass()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 12
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
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
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