Completed
Pull Request — master (#14)
by Brent
17:31
created

ValueObject::getPublicProperties()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Spatie\ValueObject;
4
5
abstract class ValueObject
6
{
7
    /** @var array */
8
    protected $allValues = [];
9
10
    /** @var array */
11
    protected $exceptKeys = [];
12
13
    /** @var array */
14
    protected $onlyKeys = [];
15
16
    public function __construct(array $parameters)
17
    {
18
        $class = new ValueObjectDefinition($this);
19
20
        $properties = $class->getValueObjectProperties();
21
22
        foreach ($properties as $property) {
23
            $value = $parameters[$property->getName()] ?? null;
24
25
            $property->set($value);
26
27
            unset($parameters[$property->getName()]);
28
29
            $this->allValues[$property->getName()] = $property->getValue($this);
30
        }
31
32
        if (count($parameters)) {
33
            throw ValueObjectError::unknownProperties(array_keys($parameters), $class);
34
        }
35
    }
36
37
    public function all(): array
38
    {
39
        return $this->allValues;
40
    }
41
42
    /**
43
     * @param string ...$keys
44
     *
45
     * @return static
46
     */
47
    public function only(string ...$keys): ValueObject
48
    {
49
        $valueObject = clone $this;
50
51
        $valueObject->onlyKeys = array_merge($this->onlyKeys, $keys);
52
53
        return $valueObject;
54
    }
55
56
    /**
57
     * @param string ...$keys
58
     *
59
     * @return static
60
     */
61
    public function except(string ...$keys): ValueObject
62
    {
63
        $valueObject = clone $this;
64
65
        $valueObject->exceptKeys = array_merge($this->exceptKeys, $keys);
66
67
        return $valueObject;
68
    }
69
70
    public function toArray(): array
71
    {
72
        if (count($this->onlyKeys)) {
73
            return Arr::only($this->all(), $this->onlyKeys);
74
        }
75
76
        return Arr::except($this->all(), $this->exceptKeys);
77
    }
78
}
79