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

Validation::unsetValidation()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

144
            [$formRequest, $extendedRules, $extendedMessages, $extendedAttributes] = $this->mergeRequestAndFieldRules(/** @scrutinizer ignore-type */ $formRequest, $rules, $messages, $attributes);
Loading history...
145
146
            // validate the complete request with FormRequest + controller validation + field validation (our anonymous class)
147
            return $this->checkRequestValidity($extendedRules, $extendedMessages, $extendedAttributes, $formRequest);
148
        }
149
150
        return ! empty($rules) ? $this->checkRequestValidity($rules, $messages, $attributes) : $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

150
        return ! empty($rules) ? $this->checkRequestValidity($rules, $messages, $attributes) : $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...
151
    }
152
153
    /**
154
     * Merge the form request validation with the fields validation.
155
     *
156
     * @param  FormRequest  $request
157
     * @param  array|null  $rules
158
     * @param  array|null  $messages
159
     * @param  array|null  $attributes
160
     * @return array
161
     */
162
    public function mergeRequestAndFieldRules($request, $rules = null, $messages = null, $attributes = null)
163
    {
164
        $rules = $rules ?? $this->getOperationSetting('validationRules') ?? [];
165
        $messages = $messages ?? $this->getOperationSetting('validationMessages') ?? [];
166
        $attributes = $attributes ?? $this->getOperationSetting('validationAttributes') ?? [];
167
168
        $request = (new $request)->createFrom($this->getRequest());
169
        $extendedRules = $this->mergeRules($request, $rules);
170
        $extendedMessages = array_merge($messages, $request->messages());
171
        $extendedAttributes = array_merge($attributes, $request->attributes());
172
173
        return [$request, $extendedRules, $extendedMessages, $extendedAttributes];
174
    }
175
176
    /**
177
     * Parse a FormRequest class, figure out what inputs are required
178
     * and store this knowledge in the current object.
179
     *
180
     * @param  string|array  $classOrRulesArray  Class that extends FormRequest or rules array
181
     */
182
    public function setRequiredFields($classOrRulesArray)
183
    {
184
        $requiredFields = $this->getOperationSetting('requiredFields') ?? [];
185
186
        if (is_array($classOrRulesArray)) {
187
            $rules = $classOrRulesArray;
188
        } else {
189
            $formRequest = new $classOrRulesArray();
190
            $rules = $formRequest->rules();
191
        }
192
193
        if (count($rules)) {
194
            foreach ($rules as $key => $validationRules) {
195
                if (is_string($validationRules)) {
196
                    $validationRules = explode('|', $validationRules);
197
                }
198
                if (! is_array($validationRules)) {
199
                    $validationRules = [$validationRules];
200
                }
201
                foreach ($validationRules as $rule) {
202
                    if (is_a($rule, BackpackCustomRule::class, true)) {
203
                        foreach ($rule->getFieldRules() as $customValidatorRules) {
204
                            if ($requiredFieldName = $this->checkIfRuleIsRequired($key, $customValidatorRules)) {
205
                                // Field is required, move on to next field
206
                                $requiredFields[] = $requiredFieldName;
207
                                break;
208
                            }
209
                        }
210
211
                        // Try next rule for field
212
                        continue;
213
                    }
214
215
                    if ($requiredFieldName = $this->checkIfRuleIsRequired($key, $rule)) {
216
                        // Field is required, move on to next field
217
                        $requiredFields[] = $requiredFieldName;
218
                        break;
219
                    }
220
                }
221
            }
222
        }
223
224
        // merge any previous required fields with current ones
225
        $requiredFields = array_merge($this->getOperationSetting('requiredFields') ?? [], $requiredFields);
226
227
        // since this COULD BE called twice (to support the previous syntax where developers needed to call `setValidation` after the field definition)
228
        // 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
229
        // no sense in doing it, so array_unique() it is.
230
        $requiredFields = array_unique($requiredFields);
231
232
        $this->setOperationSetting('requiredFields', $requiredFields);
233
    }
234
235
    /**
236
     * Check the current object to see if an input is required
237
     * for the given operation.
238
     *
239
     * @param  string  $inputKey  Field or input name.
240
     * @param  string  $operation  create / update
241
     * @return bool
242
     */
243
    public function isRequired($inputKey)
244
    {
245
        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

245
        if (! $this->/** @scrutinizer ignore-call */ hasOperationSetting('requiredFields')) {
Loading history...
246
            return false;
247
        }
248
249
        if (Str::contains($inputKey, '.')) {
250
            $inputKey = Str::dotsToSquareBrackets($inputKey, ['*']);
251
        }
252
253
        return in_array($inputKey, $this->getOperationSetting('requiredFields'));
254
    }
255
256
    /**
257
     * Add the validation setup by developer in field `validationRules` to the crud validation.
258
     *
259
     * @param  array  $field  - the field we want to get the validation from.
260
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
261
     */
262
    private function setupFieldValidation($field, $parent = false)
263
    {
264
        [$rules, $messages, $attributes] = $this->getValidationDataFromField($field, $parent);
265
266
        if (! empty($rules)) {
267
            $this->setValidation($rules, $messages, $attributes);
268
        }
269
    }
270
271
    /**
272
     * Return the messages for the fields and subfields in the current crud panel.
273
     *
274
     * @param  array  $fields
275
     * @return array
276
     */
277
    private function getValidationMessagesFromFieldsAndSubfields($fields)
278
    {
279
        $messages = [];
280
        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

280
        collect(/** @scrutinizer ignore-type */ $fields)
Loading history...
281
            ->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

281
            ->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...
282
                // only keep fields where 'validationMessages' OR there are subfields
283
                return array_key_exists('validationMessages', $value) || array_key_exists('subfields', $value);
284
            })->each(function ($item, $key) use (&$messages) {
285
                if (isset($item['validationMessages'])) {
286
                    foreach ($item['validationMessages'] as $rule => $message) {
287
                        $messages[$key.'.'.$rule] = $message;
288
                    }
289
                }
290
                // add messages from subfields
291
                if (array_key_exists('subfields', $item)) {
292
                    $subfieldsWithValidationMessages = array_filter($item['subfields'], function ($subfield) {
293
                        return array_key_exists('validationRules', $subfield);
294
                    });
295
296
                    foreach ($subfieldsWithValidationMessages as $subfield) {
297
                        foreach ($subfield['validationMessages'] ?? [] as $rule => $message) {
298
                            $messages[$item['name'].'.*.'.$subfield['name'].'.'.$rule] = $message;
299
                        }
300
                    }
301
                }
302
            })->toArray();
303
304
        return $messages;
305
    }
306
307
    /**
308
     * Return the attributes for the fields and subfields in the current crud panel.
309
     *
310
     * @param  array  $fields
311
     * @return array
312
     */
313
    private function getValidationAttributesFromFieldsAndSubfields($fields)
314
    {
315
        $attributes = [];
316
        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

316
        collect(/** @scrutinizer ignore-type */ $fields)
Loading history...
317
            ->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

317
            ->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...
318
                // only keep fields where 'validationAttribute' exists OR there are subfields
319
                return array_key_exists('validationAttribute', $value) || array_key_exists('subfields', $value);
320
            })->each(function ($item, $key) use (&$attributes) {
321
                if (isset($item['validationAttribute'])) {
322
                    $attributes[$key] = $item['validationAttribute'];
323
                }
324
                // add attributes from subfields
325
                if (array_key_exists('subfields', $item)) {
326
                    $subfieldsWithValidationAttribute = array_filter($item['subfields'], function ($subfield) {
327
                        return array_key_exists('validationAttribute', $subfield);
328
                    });
329
330
                    foreach ($subfieldsWithValidationAttribute as $subfield) {
331
                        $attributes[$item['name'].'.*.'.$subfield['name']] = $subfield['validationAttribute'];
332
                    }
333
                }
334
            })->toArray();
335
336
        return $attributes;
337
    }
338
339
    /**
340
     * Return the rules for the fields and subfields in the current crud panel.
341
     *
342
     * @param  array  $fields
343
     * @return array
344
     */
345
    private function getValidationRulesFromFieldsAndSubfields($fields)
346
    {
347
        $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

347
        $rules = collect(/** @scrutinizer ignore-type */ $fields)
Loading history...
348
            ->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

348
            ->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...
349
                // only keep fields where 'validationRules' OR there are subfields
350
                return array_key_exists('validationRules', $value) || array_key_exists('subfields', $value);
351
            })->map(function ($item, $key) {
352
                $validationRules = [];
353
                // only keep the rules, not the entire field definition
354
                if (isset($item['validationRules'])) {
355
                    $validationRules[$key] = $item['validationRules'];
356
                }
357
                // add validation rules for subfields
358
                if (array_key_exists('subfields', $item)) {
359
                    $subfieldsWithValidation = array_filter($item['subfields'], function ($subfield) {
360
                        return array_key_exists('validationRules', $subfield);
361
                    });
362
363
                    foreach ($subfieldsWithValidation as $subfield) {
364
                        $validationRules[$item['name'].'.*.'.$subfield['name']] = $subfield['validationRules'];
365
                    }
366
                }
367
368
                return $validationRules;
369
            })->toArray();
370
371
        return array_merge(...array_values($rules));
372
    }
373
374
    /**
375
     * Return the array of rules and messages with the validation key accordingly set
376
     * to match the field or the subfield accordingly.
377
     *
378
     * @param  array  $field  - the field we want to get the rules and messages from.
379
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
380
     */
381
    private function getValidationDataFromField($field, $parent = false)
382
    {
383
        $rules = [];
384
        $messages = [];
385
        $attributes = [];
386
387
        foreach ((array) $field['name'] as $fieldName) {
388
            if ($parent) {
389
                $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

389
                $fieldName = /** @scrutinizer ignore-type */ $parent.'.*.'.$fieldName;
Loading history...
390
            }
391
392
            if (isset($field['validationRules'])) {
393
                $rules[$fieldName] = $field['validationRules'];
394
            }
395
            if (isset($field['validationMessages'])) {
396
                foreach ($field['validationMessages'] as $validator => $message) {
397
                    $messages[$fieldName.'.'.$validator] = $message;
398
                }
399
            }
400
            if (isset($field['validationAttribute'])) {
401
                $attributes[$fieldName] = $field['validationAttribute'];
402
            }
403
        }
404
405
        return [$rules, $messages, $attributes];
406
    }
407
408
    /**
409
     * Return an array containing the request rules and the field/controller rules merged.
410
     * The rules in request will take precedence over the ones in controller/fields.
411
     *
412
     * @param  \Illuminate\Http\Request  $request
413
     * @param  array  $rules
414
     * @return array
415
     */
416
    private function mergeRules($request, $rules)
417
    {
418
        $extendedRules = [];
419
        $requestRules = $this->getRequestRulesAsArray($request);
420
421
        $rules = $this->getRulesAsArray($rules);
422
423
        foreach ($requestRules as $ruleKey => $rule) {
424
            $extendedRules[$ruleKey] = array_key_exists($ruleKey, $rules) ? array_merge($rule, $this->getRulesAsArray($rules[$ruleKey])) : $rule;
425
            unset($rules[$ruleKey]);
426
        }
427
428
        return array_merge($rules, $extendedRules);
429
    }
430
431
    /**
432
     * Return the request rules as an array of rules if developer provided a rule string configuration.
433
     *
434
     * @param  \Illuminate\Http\Request  $request
435
     * @return array
436
     */
437
    private function getRequestRulesAsArray($request)
438
    {
439
        $requestRules = [];
440
        foreach ($request->rules() as $ruleKey => $rule) {
441
            $requestRules[$ruleKey] = $this->getRulesAsArray($rule);
442
        }
443
444
        return $requestRules;
445
    }
446
447
    /**
448
     * Checks if the request is valid against the rules.
449
     *
450
     * @param  array  $rules
451
     * @param  array  $messages
452
     * @param  \Illuminate\Http\Request|null  $request
453
     * @return \Illuminate\Http\Request
454
     */
455
    private function checkRequestValidity($rules, $messages, $attributes, $request = null)
456
    {
457
        $request = $request ?? $this->getRequest();
458
        $request->validate($rules, $messages, $attributes);
459
460
        return $request;
461
    }
462
463
    /**
464
     * Check if the given rule is a required rule.
465
     *
466
     * @param  string  $key
467
     * @param  string  $rule
468
     * @return string|bool
469
     */
470
    private function checkIfRuleIsRequired($key, $rule)
471
    {
472
        if (
473
            (is_string($rule) && strpos($rule, 'required') !== false && strpos($rule, 'required_') === false) ||
474
            (is_array($rule) && array_search('required', $rule) !== false && array_search('required_', $rule) === false)
475
        ) {
476
            if (Str::contains($key, '.')) {
477
                $key = Str::dotsToSquareBrackets($key, ['*']);
478
            }
479
480
            return $key;
481
        }
482
483
        return false;
484
    }
485
486
    /**
487
     * Prepare the rules as array.
488
     */
489
    private function getRulesAsArray($rules)
490
    {
491
        if (is_array($rules) || is_a($rules, BackpackCustomRule::class, true)) {
492
            return $rules;
493
        }
494
495
        return explode('|', $rules);
496
    }
497
}
498