Completed
Push — master ( dfb0e5...7151fb )
by Dominik
03:16
created

PropertyAccessor::getReflectionProperty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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