ReflectionAccessor::write()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Bdf\Serializer\PropertyAccessor;
4
5
use ReflectionProperty;
6
7
/**
8
 * ReflectionAccessor
9
 *
10
 * Use reflection to access object property
11
 */
12
class ReflectionAccessor implements PropertyAccessorInterface
13
{
14
    /**
15
     * The class name
16
     *
17
     * @var string
18
     */
19
    private $class;
20
21
    /**
22
     * The property name
23
     *
24
     * @var string
25
     */
26
    private $property;
27
28
    /**
29
     * The property reflection
30
     *
31
     * @var ReflectionProperty
32
     */
33
    private $reflection;
34
35
    /**
36
     * Constructor
37
     *
38
     * @param string $class
39
     * @param string $property
40
     */
41 188
    public function __construct(string $class, string $property)
42
    {
43 188
        $this->class = $class;
44 188
        $this->property = $property;
45 188
        $this->reflection = $this->createReflection();
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 44
    public function write($object, $value)
52
    {
53 44
        $this->reflection->setValue($object, $value);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 84
    public function read($object)
60
    {
61 84
        return $this->reflection->getValue($object);
62
    }
63
64
    /**
65
     * Create property accessor.
66
     *
67
     * @return ReflectionProperty
68
     */
69 188
    private function createReflection(): ReflectionProperty
70
    {
71 188
        $reflection = new ReflectionProperty($this->class, $this->property);
72 188
        $reflection->setAccessible(true);
73
74 188
        return $reflection;
75
    }
76
77
    /**
78
     * Dont serialize closures
79
     *
80
     * @return array
81
     */
82 2
    public function __sleep()
83
    {
84 2
        return ['class', 'property'];
85
    }
86
87
    /**
88
     * Rebuild reflection.
89
     */
90 2
    public function __wakeup()
91
    {
92 2
        $this->reflection = $this->createReflection();
93
    }
94
}
95