Completed
Push — develop ( 6b671f...4eb6c9 )
by Freddie
11:11
created

SchemaAttribute::max()   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 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of FlexPHP.
4
 *
5
 * (c) Freddie Gar <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace FlexPHP\Schema;
11
12
use Exception;
13
use FlexPHP\Schema\Constants\Keyword;
14
use FlexPHP\Schema\Constants\Rule;
15
use FlexPHP\Schema\Exception\InvalidSchemaAttributeException;
16
use FlexPHP\Schema\Validations\SchemaAttributeLogicValidation;
17
use FlexPHP\Schema\Validations\SchemaAttributeValidation;
18
19
final class SchemaAttribute implements SchemaAttributeInterface
20
{
21
    /**
22
     * @var string
23
     */
24
    private $name;
25
26
    /**
27
     * @var string
28
     */
29
    private $dataType;
30
31
    /**
32
     * @var array<string, mixed>
33
     */
34
    private $constraints = [];
35
36
    /**
37
     * @param mixed $constraints
38
     */
39 137
    public function __construct(string $name, string $dataType, $constraints = null)
40
    {
41 137
        $this->setName($name);
42 137
        $this->setDataType($dataType);
43 137
        $this->setConstraints($constraints);
44
45 137
        $this->validate();
46 99
    }
47
48 137
    public function name(): string
49
    {
50 137
        return $this->name;
51
    }
52
53 137
    public function dataType(): string
54
    {
55 137
        return $this->dataType;
56
    }
57
58 137
    public function constraints(): array
59
    {
60 137
        return $this->constraints;
61
    }
62
63 6
    public function type(): ?string
64
    {
65 6
        return $this->constraints[Rule::TYPE] ?? null;
66
    }
67
68 31
    public function isRequired(): bool
69
    {
70 31
        return (bool)($this->constraints[Rule::REQUIRED] ?? false);
71
    }
72
73 78
    public function minLength(): ?int
74
    {
75 78
        return $this->constraints[Rule::MINLENGTH] ?? null;
76
    }
77
78 73
    public function maxLength(): ?int
79
    {
80 73
        return $this->constraints[Rule::MAXLENGTH] ?? null;
81
    }
82
83 32
    public function minCheck(): ?int
84
    {
85 32
        return $this->constraints[Rule::MINCHECK] ?? null;
86
    }
87
88 31
    public function maxCheck(): ?int
89
    {
90 31
        return $this->constraints[Rule::MAXCHECK] ?? null;
91
    }
92
93 62
    public function min(): ?int
94
    {
95 62
        return $this->constraints[Rule::MIN] ?? null;
96
    }
97
98 59
    public function max(): ?int
99
    {
100 59
        return $this->constraints[Rule::MAX] ?? null;
101
    }
102
103 6
    public function equalTo(): ?string
104
    {
105 6
        return $this->constraints[Rule::EQUALTO] ?? null;
106
    }
107
108 116
    public function isPk(): bool
109
    {
110 116
        return (bool)($this->constraints[Rule::PRIMARYKEY] ?? false);
111
    }
112
113 111
    public function isAi(): bool
114
    {
115 111
        return (bool)($this->constraints[Rule::AUTOINCREMENT] ?? false);
116
    }
117
118 24
    public function isFk(): bool
119
    {
120 24
        return (bool)($this->constraints[Rule::FOREIGNKEY] ?? false);
121
    }
122
123 9
    public function fkTable(): ?string
124
    {
125 9
        return $this->constraints[Rule::FOREIGNKEY]['table'] ?? null;
126
    }
127
128 9
    public function fkId(): ?string
129
    {
130 9
        return $this->constraints[Rule::FOREIGNKEY]['id'] ?? null;
131
    }
132
133 9
    public function fkName(): ?string
134
    {
135 9
        return $this->constraints[Rule::FOREIGNKEY]['name'] ?? null;
136
    }
137
138 110
    public function isCa(): bool
139
    {
140 110
        return (bool)($this->constraints[Rule::CREATEDAT] ?? false);
141
    }
142
143 109
    public function isUa(): bool
144
    {
145 109
        return (bool)($this->constraints[Rule::UPDATEDAT] ?? false);
146
    }
147
148 107
    public function isCb(): bool
149
    {
150 107
        return (bool)($this->constraints[Rule::CREATEDBY] ?? false);
151
    }
152
153 105
    public function isUb(): bool
154
    {
155 105
        return (bool)($this->constraints[Rule::UPDATEDBY] ?? false);
156
    }
157
158 110
    public function isBlameAt(): bool
159
    {
160 110
        return $this->isCa() || $this->isUa();
161
    }
162
163 107
    public function isBlameBy(): bool
164
    {
165 107
        return $this->isCb() || $this->isUb();
166
    }
167
168 28
    public function isBlame(): bool
169
    {
170 28
        return $this->isBlameAt() || $this->isBlameBy();
171
    }
172
173 137
    public function properties(): array
174
    {
175
        return [
176 137
            Keyword::NAME => $this->name(),
177 137
            Keyword::DATATYPE => $this->dataType(),
178 137
            Keyword::CONSTRAINTS => $this->constraints(),
179
        ];
180
    }
181
182 91
    public function typeHint(): string
183
    {
184
        $typeHintByDataType = [
185 91
            'smallint' => 'int',
186
            'integer' => 'int',
187
            'float' => 'float',
188
            'double' => 'float',
189
            'bool' => 'bool',
190
            'boolean' => 'bool',
191
            'date' => '\DateTime',
192
            'date_immutable' => '\DateTimeImmutable',
193
            'datetime' => '\DateTime',
194
            'datetime_immutable' => '\DateTimeImmutable',
195
            'datetimetz' => '\DateTime',
196
            'datetimetz_immutable' => '\DateTimeImmutable',
197
            'time' => '\DateTime',
198
            'time_immutable' => '\DateTimeImmutable',
199
            'array' => 'array',
200
            'simple_array' => 'array',
201
            'json_array' => 'array',
202
        ];
203
204 91
        if (isset($typeHintByDataType[$this->dataType()])) {
205 60
            return $typeHintByDataType[$this->dataType()];
206
        }
207
208 36
        return 'string';
209
    }
210
211 137
    private function validate(): void
212
    {
213
        try {
214 137
            (new SchemaAttributeValidation($this->properties()))->validate();
215 134
            (new SchemaAttributeLogicValidation($this))->validate();
216 39
        } catch (Exception $e) {
217 39
            throw new InvalidSchemaAttributeException(
218 39
                \sprintf('Attribute %s > %s', $this->name(), $e->getMessage())
219
            );
220
        }
221 99
    }
222
223 137
    private function setName(string $name): void
224
    {
225 137
        $this->name = $name;
226 137
    }
227
228 137
    private function setDataType(string $dataType): void
229
    {
230 137
        $this->dataType = $dataType;
231 137
    }
232
233
    /**
234
     * @param mixed $constraints
235
     */
236 137
    private function setConstraints($constraints): void
237
    {
238 137
        if (!empty($constraints)) {
239 115
            if (\is_string($constraints)) {
240 74
                $this->setConstraintsFromString($constraints);
241
            } else {
242 41
                $this->setConstraintsFromArray($constraints);
243
            }
244
        }
245 137
    }
246
247 74
    private function setConstraintsFromString(string $constraints): void
248
    {
249 74
        $this->setConstraintsFromArray($this->getConstraintsFromString($constraints));
250 74
    }
251
252 115
    private function setConstraintsFromArray(array $constraints): void
253
    {
254 115
        $this->constraints = $this->getConstraintsCast($constraints);
255 115
    }
256
257 74
    private function getConstraintsFromString(string $constraints): array
258
    {
259 74
        $_constraints = \explode('|', $constraints);
260
261
        /** @var mixed $_constraint */
262 74
        foreach ($_constraints as $index => $_constraint) {
263 74
            $_rule = \explode(':', $_constraint);
264
265 74
            if (\count($_rule) === 2) {
266 55
                [$_name, $_options] = $_rule;
267
268 55
                if (Rule::FOREIGNKEY !== $_name && \strpos($_options, ',') !== false) { // Range
269 2
                    [$min, $max] = \explode(',', $_options);
270 2
                    $_options = \compact('min', 'max');
271 53
                } elseif (\preg_match('/^false$/i', $_options)) { // False as string
272 12
                    $_options = false;
273 45
                } elseif (\preg_match('/^true$/i', $_options)) { // True as string
274 12
                    $_options = true;
275
                }
276
277 55
                $_constraints[$_name] = $_options;
278
            } else {
279 31
                $_constraints[$_rule[0]] = true;
280
            }
281
282 74
            unset($_constraints[$index]);
283
        }
284
285 74
        return $_constraints;
286
    }
287
288 115
    private function getConstraintsCast(array $constraints): array
289
    {
290 115
        foreach ($constraints as $name => $value) {
291 115
            if (\is_int($name)) {
292 12
                $constraints[$value] = true;
293 12
                unset($constraints[$name]);
294 108
            } elseif ($name === Rule::CHECK || $name === Rule::LENGTH) {
295 4
                $constraints['min' . $name] = (int)$value['min'];
296 4
                $constraints['max' . $name] = (int)$value['max'];
297 4
                unset($constraints[$name]);
298 104
            } elseif ($name === Rule::FOREIGNKEY && \is_string($value)) {
299 10
                $constraints[$name] = $this->getFkOptions($value);
300
            } else {
301 115
                $constraints[$name] = \is_numeric($value) ? (int)$value : $value;
302
            }
303
        }
304
305 115
        return $constraints;
306
    }
307
308 10
    private function getFkOptions(string $constraint): array
309
    {
310 10
        $_vars = \explode(',', $constraint);
311 10
        $fkName = 'name';
312 10
        $fkId = 'id';
313
314 10
        switch (\count($_vars)) {
315 10
            case 3:
316 2
                [$fkTable, $fkName, $fkId] = $_vars;
317
318 2
                break;
319 8
            case 2:
320 4
                [$fkTable, $fkName] = $_vars;
321
322 4
                break;
323
            default:
324 4
                [$fkTable] = $_vars;
325
326 4
                break;
327
        }
328
329
        return [
330 10
            'table' => $fkTable,
331 10
            'name' => $fkName,
332 10
            'id' => $fkId,
333
        ];
334
    }
335
}
336