Passed
Push — master ( b21086...64a3a8 )
by K
13:26
created

RequiredFieldsValidationStrategy::validate()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 8.8333
cc 7
nc 13
nop 1
crap 7
1
<?php declare(strict_types=1);
2
3
namespace PerfectApp\Validation;
4
5
/**
6
 *
7
 */
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)
23
    {
24 6
        $this->requiredFields = $requiredFields;
25 6
        $this->errors = [];
26
    }
27
28
    /**
29
     * @param $data
30
     * @return bool
31
     */
32 6
    public function validate($data): bool
33
    {
34 6
        $this->errors = [];
35
36 6
        foreach ($this->requiredFields as $field) {
37 6
            $isFieldEmpty = !isset($data[$field]) || empty($data[$field]);
38 6
            $isFieldArrayWithEmptyValues = isset($data[$field]) && is_array($data[$field]) && array_filter($data[$field]) === [];
39
40 6
            if ($isFieldEmpty || $isFieldArrayWithEmptyValues) {
41 4
                $msg = ucwords(str_replace('_', ' ', $field));
42 4
                $this->errors[$field] = $msg . ' is required.';
43
            }
44
        }
45
46 6
        return empty($this->errors); // Validation passed if no errors
47
    }
48
49
    /**
50
     * @return array
51
     */
52 3
    public function getErrors(): array
53
    {
54 3
        return $this->errors;
55
    }
56
}
57