AbstractStructBase::setPropertyValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WsdlToPhp\PackageBase;
6
7
use InvalidArgumentException;
8
use JsonSerializable;
9
use ReflectionClass;
10
11
abstract class AbstractStructBase implements StructInterface, JsonSerializable
12
{
13
    /**
14
     * Returns the properties of this object
15
     * @return mixed[]
16
     */
17 2
    public function jsonSerialize(): array
18
    {
19 2
        return \get_object_vars($this);
20
    }
21
22
    /**
23
     * Generic method called when an object has been exported with var_export() functions
24
     * It allows to return an object instantiated with the values
25
     * @param array $array the exported values
26
     * @return self
27
     */
28 6
    public static function __set_state(array $array): StructInterface
29
    {
30 6
        $reflection = new ReflectionClass(get_called_class());
31 6
        $object = $reflection->newInstance();
32 6
        foreach ($array as $name => $value) {
33 6
            $object->setPropertyValue($name, $value);
34
        }
35
36 4
        return $object;
37
    }
38
39
    /**
40
     * Generic method setting value
41
     * @throws InvalidArgumentException
42
     * @param string $name property name to set
43
     * @param mixed $value property value to use
44
     * @return self
45
     * @internal
46
     */
47 28
    public function setPropertyValue(string $name, $value): self
48
    {
49 28
        $setMethod = 'set' . ucfirst($name);
50 28
        if (method_exists($this, $setMethod)) {
51 28
            $this->$setMethod($value);
52
        } else {
53 2
            throw new InvalidArgumentException(sprintf('Setter does not exist for "%s" property', $name));
54
        }
55
56 28
        return $this;
57
    }
58
59
    /**
60
     * Generic method getting value
61
     * @throws InvalidArgumentException
62
     * @param string $name property name to get
63
     * @return mixed
64
     * @internal
65
     */
66 28
    public function getPropertyValue(string $name)
67
    {
68 28
        $getMethod = 'get' . ucfirst($name);
69 28
        if (method_exists($this, $getMethod)) {
70 26
            return $this->$getMethod();
71
        }
72
73 2
        throw new InvalidArgumentException(sprintf('Getter does not exist for "%s" property', $name));
74
    }
75
76
    /**
77
     * Default string representation of current object. Don't want to expose any sensible data
78
     * @return string
79
     */
80 4
    public function __toString(): string
81
    {
82 4
        return get_called_class();
83
    }
84
}
85