PropertyAccessor   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 28
c 3
b 0
f 0
dl 0
loc 76
ccs 32
cts 32
cp 1
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getValue() 0 17 2
A __construct() 0 3 1
A getClass() 0 14 5
A setValue() 0 17 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
    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