BaseValidator::validate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php namespace Usman\Guardian\Validators;
2
3
use Illuminate\Validation\Factory;
4
use Usman\Guardian\Validators\Exceptions\ValidationException;
5
use Usman\Guardian\Validators\Interfaces\BaseValidatorInterface;
6
7
abstract class BaseValidator implements BaseValidatorInterface {
8
9
    /**
10
     * Represents the data to be validated.
11
     * 
12
     * @var array
13
     */
14
    protected $fields;
15
16
    /**
17
     * Rules for data validation
18
     * 
19
     * @var array
20
     */
21
    protected $rules;
22
23
    /**
24
     * The validator instance.
25
     * 
26
     * @var Factory
27
     */
28
    protected $validator;
29
30
    /**
31
     * Creates an instance of the class.
32
     * 
33
     * @param Factory $validator
34
     */
35
    public function __construct(Factory $validator)
36
    {
37
        $this->validator = $validator;
38
    }
39
40
    /**
41
     * Validates the data.
42
     * 
43
     * @param  string $type type of validation create/update.
44
     * @throws ValidationException
45
     * @return boolean
46
     */
47
    public function validate($type)
48
    {
49
        $v = $this->validator->make($this->fields,$this->rules[$type]);
50
        
51
        if($v->fails())
52
        {
53
            throw new ValidationException($v->errors());
54
        }
55
        else
56
        {
57
            return true;
58
        }
59
    }
60
61
    /**
62
     * Sets the fields to be validated.
63
     * 
64
     * @param array $fields
65
     */
66
    public function setFields(array $fields)
67
    {
68
        $this->fields = $fields;
69
        return $this;
70
    }
71
72
    /**
73
     * Adds additional rules for data validation.
74
     * 
75
     * @param string $type
76
     * @param string $field
77
     * @param string $rule
78
     */
79
    public function addRule($type, $field, $rule)
80
    {
81
        $this->rules[$type][$field] = $rule;
82
    }
83
84
}