Total Complexity | 7 |
Total Lines | 48 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php declare(strict_types=1); |
||
8 | class RequiredFieldsValidationStrategy implements ValidationStrategy |
||
9 | { |
||
10 | /** |
||
11 | * @var array |
||
12 | */ |
||
13 | private array $requiredFields; |
||
14 | /** |
||
15 | * @var array |
||
16 | */ |
||
17 | private array $errors; |
||
18 | |||
19 | /** |
||
20 | * @param array $requiredFields |
||
21 | */ |
||
22 | 6 | public function __construct(array $requiredFields) |
|
26 | } |
||
27 | |||
28 | /** |
||
29 | * @param array $data |
||
30 | * @return bool |
||
31 | */ |
||
32 | 6 | public function validate(array $data): bool |
|
33 | { |
||
34 | 6 | $this->errors = []; |
|
35 | |||
36 | 6 | foreach ($this->requiredFields as $field) { |
|
37 | 6 | $fieldValue = $data[$field] ?? null; |
|
38 | 6 | $isFieldEmpty = empty($fieldValue); |
|
39 | 6 | $isFieldArrayWithEmptyValues = is_array($fieldValue) && array_filter($fieldValue) === []; |
|
40 | |||
41 | 6 | if ($isFieldEmpty || $isFieldArrayWithEmptyValues) { |
|
42 | 4 | $msg = ucwords(str_replace('_', ' ', $field)); |
|
43 | 4 | $this->errors[$field] = $msg . ' is required.'; |
|
44 | } |
||
45 | } |
||
46 | |||
47 | 6 | return empty($this->errors); // Validation passed if no errors |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * @return array |
||
52 | */ |
||
53 | 3 | public function getErrors(): array |
|
56 | } |
||
57 | } |
||
58 |