Model::__isset()   A
last analyzed

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