PropertyAccessor::getClass()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
nc 3
nop 1
dl 0
loc 14
ccs 5
cts 5
cp 1
crap 4
rs 10
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