MethodAccessor::write()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Bdf\Serializer\PropertyAccessor;
4
5
use InvalidArgumentException;
6
7
/**
8
 * MethodAccessor
9
 *
10
 * Manage access by a method
11
 */
12
class MethodAccessor implements PropertyAccessorInterface
13
{
14
    /**
15
     * The getter method name
16
     *
17
     * @var string|null
18
     */
19
    private $getter;
20
21
    /**
22
     * The setter method name
23
     *
24
     * @var string|null
25
     */
26
    private $setter;
27
28
    /**
29
     * The property name
30
     *
31
     * @var string
32
     */
33
    private $property;
34
35
    /**
36
     * Constructor
37
     *
38
     * @param string $class
39
     * @param string $property
40
     * @param string|null $getter  Set to false to desactivate
41
     * @param string|null $setter  Set to false to desactivate
42
     */
43 22
    public function __construct(string $class, string $property, string $getter = null, string $setter = null)
44
    {
45 22
        $this->property = $property;
46 22
        $this->getter = $getter;
47 22
        $this->setter = $setter;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 6
    public function write($object, $value)
54
    {
55 6
        if (!$this->setter) {
56 2
            throw new InvalidArgumentException('Could not find setter method for "'.$this->property.'"');
57
        }
58
59 4
        $object->{$this->setter}($value);
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 8
    public function read($object)
66
    {
67 8
        if (!$this->getter) {
68 2
            throw new InvalidArgumentException('Could not find getter method for "'.$this->property.'"');
69
        }
70
71 6
        return $object->{$this->getter}();
72
    }
73
}
74