Test Failed
Push — master ( 30c99c...b8e71f )
by Travis
02:31
created

AbstractFieldRuleSet::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 4
nop 3
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Telkins\Validation;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Illuminate\Support\Facades\Validator;
7
use Telkins\Validation\Contracts\FieldRuleSetContract;
8
9
/**
10
 * Source/inspiration: https://medium.com/@juampi92/laravel-5-5-validation-ruleception-rule-inside-rule-2762d2cf4471
11
 */
12
abstract class AbstractFieldRuleSet implements Rule, FieldRuleSetContract
13
{
14
    protected $data = [];
15
16
    protected $validator;
17
18
    public function __construct(array $data = [])
19
    {
20
        $this->data = $data;
21
    }
22
23
    /**
24
     * Determine if the validation rule passes.
25
     *
26
     * @param  string  $attribute
27
     * @param  mixed  $value
28
     * @return bool
29
     */
30
    public function passes($attribute, $value)
31
    {
32
        return $this->validate($value, $this->rules(), $attribute);
33
    }
34
35
    abstract public function rules() : array;
36
37
    /**
38
     * @param mixed $value
39
     * @param array|string|Rule $rules
40
     * @param string $name Name of the property (optional)
41
     *
42
     * @return boolean
43
     */
44
    protected function validate($value, $rules, $name = 'variable')
45
    {
46
        if (!is_string($rules) && !is_array($rules)) {
47
            $rules = [$rules];
48
        }
49
50
        $data = empty($this->data) ? [$name => $value] : $this->data;
51
52
        $this->validator = Validator::make($data, [$name => $rules]);
53
54
        return $this->validator->passes();
55
    }
56
57
    /**
58
     * Get the validation error message.
59
     *
60
     * @return string
61
     */
62
    public function message()
63
    {
64
        $errors = $this->validator->errors();
65
66
        if ($errors->any()) {
67
            return $errors->first();
68
        }
69
        
70
        return 'The :attribute is not valid.';
71
    }
72
}
73