PropertyAccessor::getValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 2
rs 9.9666
c 2
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Accessor;
6
7
use Chubbyphp\Serialization\SerializerLogicException;
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 3
    }
21
22 3
    /**
23 3
     * @param object $object
24
     *
25
     * @return mixed
26
     */
27
    public function getValue($object)
28
    {
29
        $class = $this->getClass($object);
30 3
31
        if (!property_exists($class, $this->property)) {
32 3
            throw SerializerLogicException::createMissingProperty($class, $this->property);
33
        }
34 3
35 1
        $getter = \Closure::bind(
36
            function ($property) {
37
                return $this->{$property};
38 2
            },
39 2
            $object,
40 2
            $class
41 2
        );
42 2
43 2
        return $getter($this->property);
44
    }
45
46 2
    /**
47
     * @param object $object
48
     */
49
    private function getClass($object): string
50
    {
51
        if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) {
52
            if (!$object->__isInitialized()) {
53
                $object->__load();
54 3
            }
55
56 3
            /** @var \ReflectionClass $reflectionParentClass */
57 1
            $reflectionParentClass = (new \ReflectionClass($object))->getParentClass();
58 1
59
            return $reflectionParentClass->getName();
60
        }
61 1
62
        return get_class($object);
63
    }
64
}
65