-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAttribute.php
More file actions
123 lines (105 loc) · 2.93 KB
/
Attribute.php
File metadata and controls
123 lines (105 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php declare(strict_types=1);
namespace Igni\Annotation\MetaData;
final class Attribute
{
private $name;
private $required;
private $type;
private $enum;
private $validate = true;
public function __construct(string $name, $type = 'mixed', bool $required = true)
{
$this->name = $name;
$this->type = $type;
$this->required = $required;
}
public function getName() : string
{
return $this->name;
}
public function getType() : string
{
if (is_array($this->type)) {
return end($this->type) . '[]';
}
return $this->type;
}
public function disableValidation() : void
{
$this->validate = false;
}
public function isRequired() : bool
{
return $this->required;
}
public function isEnum() : bool
{
return $this->enum !== null;
}
public function enumerate(array $values) : void
{
$this->enum = $values;
}
public function validate($value) : bool
{
if (!$this->validate) {
return true;
}
if (!$this->required && $value === null) {
return true;
}
if ($value === null) {
return false;
}
if ($this->isEnum()) {
if (is_array($this->type)) {
foreach ($value as $item) {
if (!in_array($item, $this->enum)) {
return false;
}
}
return true;
}
return in_array($value, $this->enum);
}
if (!$this->validateType($this->type, $value)) {
return false;
}
return true;
}
private function validateType($type, $value) : bool
{
switch (true) {
case $type === 'mixed' || $type === ['mixed']:
return true;
case $type === 'string':
return is_string($value);
case $type === 'boolean':
case $type === 'bool':
return is_bool($value);
case $type === 'int':
case $type === 'integer':
return is_int($value);
case $type === 'double':
case $type === 'float':
return is_float($value);
case $type === 'object':
return is_object($value);
case is_array($type):
if (!is_array($value)) {
return false;
}
foreach ($value as $item) {
if (!$this->validateType(end($type), $item)) {
return false;
}
}
return true;
case is_string($type) && class_exists($type):
return $value instanceof $type;
// Ignore unknown type annotation
default:
return false;
}
}
}