Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Passed
Push — upload-validation ( 199e68...d8ff11 )
by Pedro
11:25
created

Validation::validateRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 20
rs 9.9666
1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
use Backpack\CRUD\app\Library\Uploaders\Validation\ValidBackpackUpload;
0 ignored issues
show
Bug introduced by
The type Backpack\CRUD\app\Librar...ion\ValidBackpackUpload was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Illuminate\Foundation\Http\FormRequest;
7
use Illuminate\Support\Str;
8
9
trait Validation
10
{
11
    /**
12
     * Adds the required rules from an array and allows validation of that array.
13
     *
14
     * @param  array  $requiredFields
15
     */
16
    public function setValidationFromArray(array $rules, array $messages = [])
17
    {
18
        $this->setRequiredFields($rules);
19
        $this->setOperationSetting('validationRules', array_merge($this->getOperationSetting('validationRules') ?? [], $rules));
0 ignored issues
show
Bug introduced by
It seems like getOperationSetting() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

19
        $this->setOperationSetting('validationRules', array_merge($this->/** @scrutinizer ignore-call */ getOperationSetting('validationRules') ?? [], $rules));
Loading history...
Bug introduced by
It seems like setOperationSetting() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

19
        $this->/** @scrutinizer ignore-call */ 
20
               setOperationSetting('validationRules', array_merge($this->getOperationSetting('validationRules') ?? [], $rules));
Loading history...
20
        $this->setOperationSetting('validationMessages', array_merge($this->getOperationSetting('validationMessages') ?? [], $messages));
21
    }
22
23
    /**
24
     * Take the rules defined on fields and create a validation
25
     * array from them.
26
     */
27
    public function setValidationFromFields()
28
    {
29
        $fields = $this->getOperationSetting('fields');
30
31
        // construct the validation rules array
32
        // (eg. ['name' => 'required|min:2'])
33
        $rules = $this->getValidationRulesFromFieldsAndSubfields($fields);
34
35
        // construct the validation messages array
36
        // (eg. ['title.required' => 'You gotta write smth man.'])
37
        $messages = $this->getValidationMessagesFromFieldsAndSubfields($fields);
38
39
        $this->setValidationFromArray($rules, $messages);
40
    }
41
42
    /**
43
     * Mark a FormRequest file as required for the current operation, in Settings.
44
     * Adds the required rules to an array for easy access.
45
     *
46
     * @param  string  $class  Class that extends FormRequest
47
     */
48
    public function setValidationFromRequest($class)
49
    {
50
        $this->setFormRequest($class);
51
        $this->setRequiredFields($class);
52
    }
53
54
    /**
55
     * Mark a FormRequest file as required for the current operation, in Settings.
56
     * Adds the required rules to an array for easy access.
57
     *
58
     * @param  string|array  $classOrRulesArray  Class that extends FormRequest or array of validation rules
59
     * @param  array  $messages  Array of validation messages.
60
     */
61
    public function setValidation($classOrRulesArray = false, $messages = [])
62
    {
63
        if (! $classOrRulesArray) {
64
            $this->setValidationFromFields();
65
        } elseif (is_array($classOrRulesArray)) {
66
            $this->setValidationFromArray($classOrRulesArray, $messages);
67
        } elseif (is_string($classOrRulesArray) && class_exists($classOrRulesArray) && is_a($classOrRulesArray, FormRequest::class, true)) {
68
            $this->setValidationFromRequest($classOrRulesArray);
69
        } else {
70
            abort(500, 'Please pass setValidation() nothing, a rules array or a FormRequest class.');
71
        }
72
    }
73
74
    /**
75
     * Remove the current FormRequest from configuration, so it will no longer be validated.
76
     */
77
    public function unsetValidation()
78
    {
79
        $this->setOperationSetting('formRequest', false);
80
        $this->setOperationSetting('validationRules', []);
81
        $this->setOperationSetting('validationMessages', []);
82
        $this->setOperationSetting('requiredFields', []);
83
    }
84
85
    /**
86
     * Remove the current FormRequest from configuration, so it will no longer be validated.
87
     */
88
    public function disableValidation()
89
    {
90
        $this->unsetValidation();
91
    }
92
93
    /**
94
     * Mark a FormRequest file as required for the current operation, in Settings.
95
     *
96
     * @param  string  $class  Class that extends FormRequest
97
     */
98
    public function setFormRequest($class)
99
    {
100
        $this->setOperationSetting('formRequest', $class);
101
    }
102
103
    /**
104
     * Get the current form request file, in any.
105
     * Returns null if no FormRequest is required for the current operation.
106
     *
107
     * @return string Class that extends FormRequest
108
     */
109
    public function getFormRequest()
110
    {
111
        return $this->getOperationSetting('formRequest');
112
    }
113
114
    /**
115
     * Run the authorization and validation for the current crud panel.
116
     * That authorization is gathered from 3 places:
117
     * - the FormRequest when provided.
118
     * - the rules added in the controller.
119
     * - the rules defined in the fields itself.
120
     *
121
     * @return \Illuminate\Http\Request
122
     */
123
    public function validateRequest()
124
    {
125
        $formRequest = $this->getFormRequest();
126
127
        $rules = $this->getOperationSetting('validationRules') ?? [];
128
        $messages = $this->getOperationSetting('validationMessages') ?? [];
129
130
        if ($formRequest) {
131
            // when there is no validation in the fields, just validate the form request.
132
            if (empty($rules)) {
133
                return app($formRequest);
0 ignored issues
show
Bug Best Practice introduced by
The expression return app($formRequest) also could return the type Illuminate\Contracts\Foundation\Application which is incompatible with the documented return type Illuminate\Http\Request.
Loading history...
134
            }
135
136
            [$formRequest, $extendedRules, $extendedMessages] = $this->mergeRequestAndFieldRules($formRequest, $rules, $messages);
0 ignored issues
show
Bug introduced by
$formRequest of type string is incompatible with the type Illuminate\Foundation\Http\FormRequest expected by parameter $request of Backpack\CRUD\app\Librar...eRequestAndFieldRules(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

136
            [$formRequest, $extendedRules, $extendedMessages] = $this->mergeRequestAndFieldRules(/** @scrutinizer ignore-type */ $formRequest, $rules, $messages);
Loading history...
137
138
            // validate the complete request with FormRequest + controller validation + field validation (our anonymous class)
139
            return $this->checkRequestValidity($extendedRules, $extendedMessages, $formRequest);
140
        }
141
142
        return ! empty($rules) ? $this->checkRequestValidity($rules, $messages) : $this->getRequest();
0 ignored issues
show
Bug introduced by
The method getRequest() does not exist on Backpack\CRUD\app\Librar...Panel\Traits\Validation. Did you maybe mean getRequestRulesAsArray()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

142
        return ! empty($rules) ? $this->checkRequestValidity($rules, $messages) : $this->/** @scrutinizer ignore-call */ getRequest();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
143
    }
144
145
    /**
146
     * Merge the form request validation with the fields validation.
147
     *
148
     * @param  FormRequest  $request
149
     * @param  array|null  $rules
150
     * @param  array|null  $messages
151
     * @return array
152
     */
153
    public function mergeRequestAndFieldRules($request, $rules = null, $messages = null)
154
    {
155
        $rules = $rules ?? $this->getOperationSetting('validationRules') ?? [];
156
        $messages = $messages ?? $this->getOperationSetting('validationMessages') ?? [];
157
158
        $request = (new $request)->createFrom($this->getRequest());
159
        $extendedRules = $this->mergeRules($request, $rules);
160
        $extendedMessages = array_merge($messages, $request->messages());
161
162
        return [$request, $extendedRules, $extendedMessages];
163
    }
164
165
    /**
166
     * Parse a FormRequest class, figure out what inputs are required
167
     * and store this knowledge in the current object.
168
     *
169
     * @param  string|array  $classOrRulesArray  Class that extends FormRequest or rules array
170
     */
171
    public function setRequiredFields($classOrRulesArray)
172
    {
173
        $requiredFields = $this->getOperationSetting('requiredFields') ?? [];
174
175
        if (is_array($classOrRulesArray)) {
176
            $rules = $classOrRulesArray;
177
        } else {
178
            $formRequest = new $classOrRulesArray();
179
            $rules = $formRequest->rules();
180
        }
181
182
        if (count($rules)) {
183
            foreach ($rules as $key => $validationRules) {
184
                if (is_string($validationRules)) {
185
                    $validationRules = explode('|', $validationRules);
186
                }
187
                foreach ($validationRules as $rule) {
188
                    if (is_a($rule, ValidBackpackUpload::class, true)) {
189
                        foreach ($rule->arrayRules as $arrayRule) {
190
                            $key = $this->checkIfRuleIsRequired($key, $arrayRule);
191
                            if ($key) {
192
                                $requiredFields[] = $key;
193
                            }
194
                        }
195
196
                        continue;
197
                    }
198
                    $key = $this->checkIfRuleIsRequired($key, $rule);
199
                    if ($key) {
200
                        $requiredFields[] = $key;
201
                    }
202
                }
203
            }
204
        }
205
206
        // merge any previous required fields with current ones
207
        $requiredFields = array_merge($this->getOperationSetting('requiredFields') ?? [], $requiredFields);
208
209
        // since this COULD BE called twice (to support the previous syntax where developers needed to call `setValidation` after the field definition)
210
        // and to make this change non-breaking, we are going to return an unique array. There is NO WARM returning repeated names, but there is also
211
        // no sense in doing it, so array_unique() it is.
212
        $requiredFields = array_unique($requiredFields);
213
214
        $this->setOperationSetting('requiredFields', $requiredFields);
215
    }
216
217
    /**
218
     * Check the current object to see if an input is required
219
     * for the given operation.
220
     *
221
     * @param  string  $inputKey  Field or input name.
222
     * @param  string  $operation  create / update
223
     * @return bool
224
     */
225
    public function isRequired($inputKey)
226
    {
227
        if (! $this->hasOperationSetting('requiredFields')) {
0 ignored issues
show
Bug introduced by
It seems like hasOperationSetting() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

227
        if (! $this->/** @scrutinizer ignore-call */ hasOperationSetting('requiredFields')) {
Loading history...
228
            return false;
229
        }
230
231
        if (Str::contains($inputKey, '.')) {
232
            $inputKey = Str::dotsToSquareBrackets($inputKey, ['*']);
233
        }
234
235
        return in_array($inputKey, $this->getOperationSetting('requiredFields'));
236
    }
237
238
    /**
239
     * Add the validation setup by developer in field `validationRules` to the crud validation.
240
     *
241
     * @param  array  $field  - the field we want to get the validation from.
242
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
243
     */
244
    private function setupFieldValidation($field, $parent = false)
245
    {
246
        [$rules, $messages] = $this->getValidationRulesAndMessagesFromField($field, $parent);
247
248
        if (! empty($rules)) {
249
            $this->setValidation($rules, $messages);
250
        }
251
    }
252
253
    /**
254
     * Return the messages for the fields and subfields in the current crud panel.
255
     *
256
     * @param  array  $fields
257
     * @return array
258
     */
259
    private function getValidationMessagesFromFieldsAndSubfields($fields)
260
    {
261
        $messages = [];
262
        collect($fields)
0 ignored issues
show
Bug introduced by
$fields of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

262
        collect(/** @scrutinizer ignore-type */ $fields)
Loading history...
263
            ->filter(function ($value, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

263
            ->filter(function ($value, /** @scrutinizer ignore-unused */ $key) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
264
                // only keep fields where 'validationMessages' OR there are subfields
265
                return array_key_exists('validationMessages', $value) || array_key_exists('subfields', $value);
266
            })->each(function ($item, $key) use (&$messages) {
267
                if (isset($item['validationMessages'])) {
268
                    foreach ($item['validationMessages'] as $rule => $message) {
269
                        $messages[$key.'.'.$rule] = $message;
270
                    }
271
                }
272
                // add messages from subfields
273
                if (array_key_exists('subfields', $item)) {
274
                    $subfieldsWithValidationMessages = array_filter($item['subfields'], function ($subfield) {
275
                        return array_key_exists('validationRules', $subfield);
276
                    });
277
278
                    foreach ($subfieldsWithValidationMessages as $subfield) {
279
                        foreach ($subfield['validationMessages'] ?? [] as $rule => $message) {
280
                            $messages[$item['name'].'.*.'.$subfield['name'].'.'.$rule] = $message;
281
                        }
282
                    }
283
                }
284
            })->toArray();
285
286
        return $messages;
287
    }
288
289
    /**
290
     * Return the rules for the fields and subfields in the current crud panel.
291
     *
292
     * @param  array  $fields
293
     * @return array
294
     */
295
    private function getValidationRulesFromFieldsAndSubfields($fields)
296
    {
297
        $rules = collect($fields)
0 ignored issues
show
Bug introduced by
$fields of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

297
        $rules = collect(/** @scrutinizer ignore-type */ $fields)
Loading history...
298
            ->filter(function ($value, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

298
            ->filter(function ($value, /** @scrutinizer ignore-unused */ $key) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
299
                // only keep fields where 'validationRules' OR there are subfields
300
                return array_key_exists('validationRules', $value) || array_key_exists('subfields', $value);
301
            })->map(function ($item, $key) {
302
                $validationRules = [];
303
                // only keep the rules, not the entire field definition
304
                if (isset($item['validationRules'])) {
305
                    $validationRules[$key] = $item['validationRules'];
306
                }
307
                // add validation rules for subfields
308
                if (array_key_exists('subfields', $item)) {
309
                    $subfieldsWithValidation = array_filter($item['subfields'], function ($subfield) {
310
                        return array_key_exists('validationRules', $subfield);
311
                    });
312
313
                    foreach ($subfieldsWithValidation as $subfield) {
314
                        $validationRules[$item['name'].'.*.'.$subfield['name']] = $subfield['validationRules'];
315
                    }
316
                }
317
318
                return $validationRules;
319
            })->toArray();
320
321
        return array_merge(...array_values($rules));
322
    }
323
324
    /**
325
     * Return the array of rules and messages with the validation key accordingly set
326
     * to match the field or the subfield accordingly.
327
     *
328
     * @param  array  $field  - the field we want to get the rules and messages from.
329
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
330
     */
331
    private function getValidationRulesAndMessagesFromField($field, $parent = false)
332
    {
333
        $rules = [];
334
        $messages = [];
335
336
        foreach ((array) $field['name'] as $fieldName) {
337
            if ($parent) {
338
                $fieldName = $parent.'.*.'.$fieldName;
0 ignored issues
show
Bug introduced by
Are you sure $parent of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

338
                $fieldName = /** @scrutinizer ignore-type */ $parent.'.*.'.$fieldName;
Loading history...
339
            }
340
341
            if (isset($field['validationRules'])) {
342
                $rules[$fieldName] = $field['validationRules'];
343
            }
344
            if (isset($field['validationMessages'])) {
345
                foreach ($field['validationMessages'] as $validator => $message) {
346
                    $fieldValidationName = $fieldName.'.'.$validator;
347
                    $messages[$fieldValidationName] = $message;
348
                }
349
            }
350
        }
351
352
        return [$rules, $messages];
353
    }
354
355
    /**
356
     * Return an array containing the request rules and the field/controller rules merged.
357
     * The rules in request will take precedence over the ones in controller/fields.
358
     *
359
     * @param  \Illuminate\Http\Request  $request
360
     * @param  array  $rules
361
     * @return array
362
     */
363
    private function mergeRules($request, $rules)
364
    {
365
        $extendedRules = [];
366
        $requestRules = $this->getRequestRulesAsArray($request);
367
        $rules = array_map(function ($ruleDefinition) {
368
            return is_array($ruleDefinition) ? $ruleDefinition : explode('|', $ruleDefinition);
369
        }, $rules);
370
371
        foreach ($requestRules as $ruleKey => $rule) {
372
            $extendedRules[$ruleKey] = array_key_exists($ruleKey, $rules) ? array_merge($rule, $rules[$ruleKey]) : $rule;
373
            unset($rules[$ruleKey]);
374
        }
375
376
        return array_merge($rules, $extendedRules);
377
    }
378
379
    /**
380
     * Return the request rules as an array of rules if developer provided a rule string configuration.
381
     *
382
     * @param  \Illuminate\Http\Request  $request
383
     * @return array
384
     */
385
    private function getRequestRulesAsArray($request)
386
    {
387
        $requestRules = [];
388
        foreach ($request->rules() as $ruleKey => $rule) {
389
            $requestRules[$ruleKey] = is_array($rule) ? $rule : explode('|', $rule);
390
        }
391
392
        return $requestRules;
393
    }
394
395
    /**
396
     * Checks if the request is valid against the rules.
397
     *
398
     * @param  array  $rules
399
     * @param  array  $messages
400
     * @param  \Illuminate\Http\Request|null  $request
401
     * @return \Illuminate\Http\Request
402
     */
403
    private function checkRequestValidity($rules, $messages, $request = null)
404
    {
405
        $request = $request ?? $this->getRequest();
406
        $request->validate($rules, $messages);
407
408
        return $request;
409
    }
410
411
    /**
412
     * Check if the given rule is a required rule.
413
     *
414
     * @param  string  $key
415
     * @param  string  $rule
416
     * @return string|bool
417
     */
418
    private function checkIfRuleIsRequired($key, $rule)
419
    {
420
        if (
421
            (is_string($rule) && strpos($rule, 'required') !== false && strpos($rule, 'required_') === false) ||
422
            (is_array($rule) && array_search('required', $rule) !== false && array_search('required_', $rule) === false)
423
        ) {
424
            if (Str::contains($key, '.')) {
425
                $key = Str::dotsToSquareBrackets($key, ['*']);
426
            }
427
428
            return $key;
429
        }
430
431
        return false;
432
    }
433
}
434