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

PropertyAccessor   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 56
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getValue() 0 7 1
A getClass() 0 8 3
A getReflectionProperty() 0 8 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
        $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