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

RequestModelValidator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
dl 0
loc 41
ccs 23
cts 23
cp 1
rs 10
c 1
b 0
f 0
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
A useRule() 0 8 5
A prepareRules() 0 9 3
A validate() 0 18 3
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