Test Setup Failed
Push — master ( b50703...9d91c5 )
by Dominik
06:16
created

MethodAccessor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Deserialization\Accessor;
6
7
final class MethodAccessor implements AccessorInterface
8
{
9
    /**
10
     * @var string
11
     */
12
    private $property;
13
14
    /**
15
     * @param string $property
16
     */
17
    public function __construct(string $property)
18
    {
19
        $this->property = $property;
20
    }
21
22
    /**
23
     * @param object $object
24
     * @param mixed  $value
25
     *
26
     * @throws \RuntimeException
27
     */
28
    public function setValue($object, $value)
29
    {
30
        $set = 'set'.ucfirst($this->property);
31
        if (!method_exists($object, $set)) {
32
            throw new \RuntimeException(
33
                sprintf('Missing method to set property %s on class %s', $this->property, get_class($object))
34
            );
35
        }
36
37
        return $object->$set($value);
38
    }
39
40
    /**
41
     * @param object $object
42
     *
43
     * @return mixed
44
     *
45
     * @throws \RuntimeException
46
     */
47
    public function getValue($object)
48
    {
49
        $get = 'get'.ucfirst($this->property);
50
        $has = 'has'.ucfirst($this->property);
51
        $is = 'is'.ucfirst($this->property);
52
53
        if (method_exists($object, $get)) {
54
            return $object->$get();
55
        }
56
57
        if (method_exists($object, $has)) {
58
            return $object->$has();
59
        }
60
61
        if (method_exists($object, $is)) {
62
            return $object->$is();
63
        }
64
65
        throw new \RuntimeException(
66
            sprintf('Missing method to get property %s on class %ss', $this->property, get_class($object))
67
        );
68
    }
69
}
70