PropertyAccessor::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
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
    public function __construct(string $property)
18
    {
19
        $this->property = $property;
20 6
    }
21
22 6
    /**
23 6
     * @param object $object
24
     * @param mixed  $value
25
     */
26
    public function setValue($object, $value): void
27
    {
28
        $class = $this->getClass($object);
29 3
30
        if (!property_exists($class, $this->property)) {
31 3
            throw DeserializerLogicException::createMissingProperty($class, $this->property);
32
        }
33 3
34 1
        $setter = \Closure::bind(
35
            function ($property, $value): void {
36
                $this->{$property} = $value;
37 2
            },
38 2
            $object,
39 2
            $class
40 2
        );
41 2
42 2
        $setter($this->property, $value);
43
    }
44
45 2
    /**
46 2
     * @param object $object
47
     *
48
     * @return mixed
49
     */
50
    public function getValue($object)
51
    {
52
        $class = $this->getClass($object);
53 3
54
        if (!property_exists($class, $this->property)) {
55 3
            throw DeserializerLogicException::createMissingProperty($class, $this->property);
56
        }
57 3
58 1
        $getter = \Closure::bind(
59
            function ($property) {
60
                return $this->{$property};
61 2
            },
62 2
            $object,
63 2
            $class
64 2
        );
65 2
66 2
        return $getter($this->property);
67
    }
68
69 2
    /**
70
     * @param object $object
71
     */
72
    private function getClass($object): string
73
    {
74
        if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) {
75
            if (!$object->__isInitialized()) {
76
                $object->__load();
77 6
            }
78
79 6
            $reflectionParentClass = (new \ReflectionObject($object))->getParentClass();
80 2
            if ($reflectionParentClass instanceof \ReflectionClass) {
81 2
                return $reflectionParentClass->getName();
82
            }
83
        }
84 2
85 2
        return get_class($object);
86 2
    }
87
}
88