Passed
Push — master ( fc2f89...038734 )
by compolom
02:33
created

Model::setRequired()   A

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 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Resova;
4
5
use InvalidArgumentException;
6
7
class Model
8
{
9
    /**
10
     * Model constructor.
11
     *
12
     * @param array $params
13
     */
14 3
    public function __construct(array $params = [])
15
    {
16 3
        foreach ($params as $key => $value) {
17 3
            $this->$key = $value;
18
        }
19 3
    }
20
21
    /**
22
     * List of allowed fields
23
     *
24
     * @return array
25
     */
26
    public function allowed(): array
27
    {
28
        return [];
29
    }
30
31
    /**
32
     * @var array
33
     */
34
    private $required = [];
35
36
    /**
37
     * @param array $required
38
     */
39 2
    public function setRequired(array $required): void
40
    {
41 2
        $this->required = $required;
42 2
    }
43
44
    /**
45
     * List of required fields
46
     *
47
     * @return array
48
     */
49
    public function required(): array
50
    {
51
        return $this->required;
52
    }
53
54
    /**
55
     * @var array
56
     */
57
    private $variables = [];
58
59
    /**
60
     * @param string $name
61
     *
62
     * @return mixed
63
     */
64
    public function __get(string $name)
65
    {
66
        return $this->variables[$name];
67
    }
68
69
    /**
70
     * @param string $name
71
     * @param mixed  $value
72
     *
73
     * @throws InvalidArgumentException
74
     */
75 3
    public function __set(string $name, $value)
76
    {
77 3
        if (!array_key_exists($name, $this->allowed())) {
78
            throw new InvalidArgumentException("Argument $name is not allowed [" . implode(',', $this->allowed()) . ']');
79
        }
80
81 3
        $this->variables[$name] = $value;
82 3
    }
83
84
    /**
85
     * @param string $name
86
     *
87
     * @return bool
88
     */
89
    public function __isset(string $name): bool
90
    {
91
        return isset($this->variables[$name]);
92
    }
93
94
    /**
95
     * @return array
96
     * @throws InvalidArgumentException
97
     */
98
    public function toArray(): array
99
    {
100
        $missing = array_diff_key(array_flip($this->required()), $this->variables);
101
102
        if (!empty($missing)) {
103
            throw new InvalidArgumentException('Keys missing [' . implode(',', $missing) . ']');
104
        }
105
106
        return $this->variables;
107
    }
108
}
109