Completed
Push — master ( 0365a3...8a81d1 )
by Alexey
02:12
created

Validator::errors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
4
namespace Lexuss1979\Validol;
5
6
7
use Lexuss1979\Validol\Validations\ValidationFactory;
8
9
class Validator
10
{
11
    private $validated;
12
    private $errors;
13
    private $validationFactory;
14
15 41
    public function __construct()
16
    {
17 41
        $this->validationFactory = new ValidationFactory();
18 41
    }
19
20 41
    public function validate($data, $rules)
21
    {
22 41
        $validationResult = true;
23 41
        $this->validated = [];
24 41
        $this->errors = [];
25
26 41
        $dataProvider = new DataProvider($data);
27
28 41
        foreach ($rules as $dataKey => $rule){
29 41
            $testedValue = $dataProvider->get($dataKey);
30 41
            $validations = explode(" ",$rule);
31
32 41
            $valueIsValid = true;
33 41
            foreach ($validations as $validation){
34 41
                $validation = $this->validationFactory->get($validation);
35 41
                if(!$validation->validate($testedValue)){
36 26
                    $this->errors[$dataKey][] = $validation->error();
37 26
                    $valueIsValid = false;
38
                }
39
            }
40
41 41
            if($valueIsValid) {
42 21
                $this->validated[$testedValue->name()] = $testedValue->value();
43
            } else {
44 26
                $validationResult = false;
45
            }
46
47
        }
48 41
        return $validationResult;
49
    }
50
51 4
    public function errors(){
52 4
        return $this->errors;
53
    }
54
55 3
    public function validated(){
56 3
        return $this->validated;
57
    }
58
59 1
    public static function process($data, $rules){
60 1
        $validator = new static();
61 1
        $result = $validator->validate($data, $rules);
62
63 1
        return new ValidationResult(
64 1
            $result,
65 1
            $validator->validated(),
66 1
            $validator->errors()
67
        );
68
    }
69
}