Passed
Pull Request — master (#14)
by Sergei
02:33
created

RequestModelValidator::useRule()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 4
nc 6
nop 4
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\RequestModel;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Validator\Rules;
9
10
final class RequestModelValidator
11
{
12 15
    public function validate(ValidatableModelInterface $model, array $data): array
13
    {
14 15
        $rules = $this->prepareRules(
15 15
            $data,
16 15
            $model->getRules(),
17 15
            $model->getOptionalFields(),
0 ignored issues
show
Bug introduced by
The method getOptionalFields() does not exist on Yiisoft\RequestModel\ValidatableModelInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Yiisoft\RequestModel\Str...lidatableModelInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

17
            $model->/** @scrutinizer ignore-call */ 
18
                    getOptionalFields(),
Loading history...
18 15
            $model instanceof StrictValidatableModelInterface
19
        );
20
21 15
        $errors = [];
22 15
        foreach ($rules as $field => $fieldRules) {
23 10
            $result = (new Rules($fieldRules))->validate(ArrayHelper::getValueByPath($data, $field));
24 10
            if ($result->isValid() === false) {
25 4
                $errors[$field] = $result->getErrors();
26
            }
27
        }
28
29 15
        return $errors;
30
    }
31
32 15
    private function prepareRules(array $data, array $allRules, array $optionalFields, bool $strict): array
33
    {
34 15
        $rules = [];
35 15
        foreach ($allRules as $field => $fieldRules) {
36 15
            if ($this->useRule($field, $data, $optionalFields, $strict)) {
37 10
                $rules[$field] = $fieldRules;
38
            }
39
        }
40 15
        return $rules;
41
    }
42
43 15
    private function useRule(string $field, array $data, array $optionalFields, bool $strict): bool
44
    {
45 15
        if (!in_array($field, $optionalFields)) {
46 4
            return true;
47
        }
48
49 11
        return ($strict && ArrayHelper::pathExists($data, $field)) ||
50 11
            (!$strict && !empty(ArrayHelper::getValueByPath($data, $field)));
51
    }
52
}
53