Completed
Push — master ( 328c23...368b19 )
by
unknown
07:01 queued 12s
created

Validator::validate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1.0046

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1.0046
1
<?php
2
3
namespace Proengsoft\JsValidation\Remote;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Http\JsonResponse;
7
use Illuminate\Validation\ValidationException;
8
use Illuminate\Validation\ValidationRuleParser;
9
use Proengsoft\JsValidation\Support\RuleListTrait;
10
use Illuminate\Http\Exceptions\HttpResponseException;
11
use Illuminate\Validation\Validator as BaseValidator;
12
use Proengsoft\JsValidation\Support\AccessProtectedTrait;
13
14
class Validator
15
{
16
    use AccessProtectedTrait;
17
    use RuleListTrait;
18
19
    /**
20
     * Validator extension name.
21
     */
22
    const EXTENSION_NAME = 'jsvalidation';
23
24
    /**
25
     * @var \Illuminate\Validation\Validator
26
     */
27
    protected $validator;
28
29
    /**
30
     * RemoteValidator constructor.
31
     *
32
     * @param \Illuminate\Validation\Validator $validator
33
     */
34 60
    public function __construct(BaseValidator $validator)
35
    {
36 60
        $this->validator = $validator;
37 60
    }
38
39
    /**
40
     * Validate request.
41
     *
42
     * @param $field
43
     * @param $parameters
44
     * @return void
45
     *
46
     * @throws \Illuminate\Validation\ValidationException
47
     */
48 60
    public function validate($field, $parameters = [])
49
    {
50 60
        $attribute = $this->parseAttributeName($field);
51 60
        $validationParams = $this->parseParameters($parameters);
52 60
        $validationResult = $this->validateJsRemoteRequest($attribute, $validationParams);
53
54 60
        $this->throwValidationException($validationResult, $this->validator);
55
    }
56
57
    /**
58
     * Throw the failed validation exception.
59
     *
60
     * @param mixed $result
61
     * @param \Illuminate\Validation\Validator  $validator
62
     * @return void
63
     *
64
     * @throws \Illuminate\Validation\ValidationException|\Illuminate\Http\Exceptions\HttpResponseException
65
     */
66 60
    protected function throwValidationException($result, $validator)
67
    {
68 60
        $response = new JsonResponse($result, 200);
69
70 60
        if ($result !== true && class_exists(ValidationException::class)) {
71 24
            throw new ValidationException($validator, $response);
72
        }
73
74 36
        throw new HttpResponseException($response);
75
    }
76
77
    /**
78
     *  Parse Validation input request data.
79
     *
80
     * @param $data
81
     * @return array
82
     */
83 60
    protected function parseAttributeName($data)
84
    {
85 60
        parse_str($data, $attrParts);
86 60
        $attrParts = is_null($attrParts) ? [] : $attrParts;
87 60
        $newAttr = array_keys(Arr::dot($attrParts));
0 ignored issues
show
Documentation introduced by
$attrParts is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
88
89 60
        return array_pop($newAttr);
90
    }
91
92
    /**
93
     *  Parse Validation parameters.
94
     *
95
     * @param $parameters
96
     * @return array
97
     */
98 60
    protected function parseParameters($parameters)
99
    {
100 60
        $newParams = ['validate_all' => false];
101 60
        if (isset($parameters[0])) {
102 48
            $newParams['validate_all'] = ($parameters[0] === 'true') ? true : false;
103 4
        }
104
105 60
        return $newParams;
106
    }
107
108
    /**
109
     * Validate remote Javascript Validations.
110
     *
111
     * @param $attribute
112
     * @param array $parameters
113
     * @return array|bool
114
     */
115 60
    protected function validateJsRemoteRequest($attribute, $parameters)
116
    {
117 60
        $this->setRemoteValidation($attribute, $parameters['validate_all']);
118
119 60
        $validator = $this->validator;
120 60
        if ($validator->passes()) {
121 36
            return true;
122
        }
123
124 24
        return $validator->messages()->get($attribute);
125
    }
126
127
    /**
128
     * Sets data for validate remote rules.
129
     *
130
     * @param $attribute
131
     * @param bool $validateAll
132
     * @return void
133
     */
134 60
    protected function setRemoteValidation($attribute, $validateAll = false)
135
    {
136 60
        $validator = $this->validator;
137 60
        $rules = $validator->getRules();
138 60
        $rules = isset($rules[$attribute]) ? $rules[$attribute] : [];
139 60
        if (in_array('no_js_validation', $rules)) {
140 12
            $validator->setRules([$attribute => []]);
141
142 12
            return;
143
        }
144 48
        if (! $validateAll) {
145 36
            $rules = $this->purgeNonRemoteRules($rules, $validator);
146 3
        }
147 48
        $validator->setRules([$attribute => $rules]);
148 48
    }
149
150
    /**
151
     * Remove rules that should not be validated remotely.
152
     *
153
     * @param $rules
154
     * @param BaseValidator $validator
155
     * @return mixed
156
     */
157 36
    protected function purgeNonRemoteRules($rules, $validator)
158
    {
159 36
        $protectedValidator = $this->createProtectedCaller($validator);
0 ignored issues
show
Unused Code introduced by
$protectedValidator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
160
161 36
        foreach ($rules as $i => $rule) {
162 36
            $parsedRule = ValidationRuleParser::parse([$rule]);
163 36
            if (! $this->isRemoteRule($parsedRule[0])) {
164 36
                unset($rules[$i]);
165 3
            }
166 3
        }
167
168 36
        return $rules;
169
    }
170
}
171