Passed
Push — master ( 809b2b...bcaf80 )
by Dominik
02:54
created

PropertyAccessor::getClass()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 1
crap 3
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
        $reflectionProperty = $this->getReflectionProperty($this->getClass($object));
33 2
        $reflectionProperty->setAccessible(true);
34
35 2
        return $reflectionProperty->getValue($object);
36
    }
37
38
    /**
39
     * @param object $object
40
     *
41
     * @return string
42
     */
43 3
    private function getClass($object): string
44
    {
45 3
        if (interface_exists('Doctrine\Common\Persistence\Proxy') && $object instanceof Proxy) {
46 1
            return (new \ReflectionClass($object))->getParentClass()->name;
47
        }
48
49 2
        return get_class($object);
50
    }
51
52
    /**
53
     * @param string $class
54
     *
55
     * @return \ReflectionProperty
56
     */
57 3
    private function getReflectionProperty(string $class): \ReflectionProperty
58
    {
59
        try {
60 3
            return new \ReflectionProperty($class, $this->property);
61 1
        } catch (\ReflectionException $e) {
62 1
            throw SerializerLogicException::createMissingProperty($class, $this->property);
63
        }
64
    }
65
}
66