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
Pull Request — main (#4529)
by Cristian
29:21 queued 14:43
created

Validation   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 373
Duplicated Lines 0 %

Importance

Changes 7
Bugs 5 Features 0
Metric Value
eloc 120
dl 0
loc 373
rs 4.5599
c 7
b 5
f 0
wmc 58

18 Methods

Rating   Name   Duplication   Size   Complexity  
A setValidationFromArray() 0 5 1
B getValidationMessagesFromFieldsAndSubfields() 0 28 7
A getFormRequest() 0 3 1
A setFormRequest() 0 3 1
A getValidationRulesFromFieldsAndSubfields() 0 27 5
A setValidation() 0 10 5
A unsetValidation() 0 6 1
A setValidationFromFields() 0 13 1
A disableValidation() 0 3 1
A setValidationFromRequest() 0 4 1
A getValidationRulesAndMessagesFromField() 0 22 6
A isRequired() 0 11 3
A mergeRules() 0 14 4
A getRequestRulesAsArray() 0 8 3
A validateRequest() 0 22 4
A checkRequestValidity() 0 6 1
B setRequiredFields() 0 35 11
A setupFieldValidation() 0 6 2

How to fix   Complexity   

Complex Class

Complex classes like Validation often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Validation, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
use Illuminate\Support\Str;
6
7
trait Validation
8
{
9
    /**
10
     * Adds the required rules from an array and allows validation of that array.
11
     *
12
     * @param  array  $requiredFields
13
     */
14
    public function setValidationFromArray(array $rules, array $messages = [])
15
    {
16
        $this->setRequiredFields($rules);
17
        $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

17
        $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

17
        $this->/** @scrutinizer ignore-call */ 
18
               setOperationSetting('validationRules', array_merge($this->getOperationSetting('validationRules') ?? [], $rules));
Loading history...
18
        $this->setOperationSetting('validationMessages', array_merge($this->getOperationSetting('validationMessages') ?? [], $messages));
19
    }
20
21
    /**
22
     * Take the rules defined on fields and create a validation
23
     * array from them.
24
     */
25
    public function setValidationFromFields()
26
    {
27
        $fields = $this->getOperationSetting('fields');
28
29
        // construct the validation rules array
30
        // (eg. ['name' => 'required|min:2'])
31
        $rules = $this->getValidationRulesFromFieldsAndSubfields($fields);
32
33
        // construct the validation messages array
34
        // (eg. ['title.required' => 'You gotta write smth man.'])
35
        $messages = $this->getValidationMessagesFromFieldsAndSubfields($fields);
36
37
        $this->setValidationFromArray($rules, $messages);
38
    }
39
40
    /**
41
     * Return the rules for the fields and subfields in the current crud panel.
42
     *
43
     * @param  array  $fields
44
     * @return array
45
     */
46
    private function getValidationRulesFromFieldsAndSubfields($fields)
47
    {
48
        $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

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

49
            ->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...
50
                // only keep fields where 'validationRules' OR there are subfields
51
                return array_key_exists('validationRules', $value) || array_key_exists('subfields', $value);
52
            })->map(function ($item, $key) {
53
                $validationRules = [];
54
                // only keep the rules, not the entire field definition
55
                if (isset($item['validationRules'])) {
56
                    $validationRules[$key] = $item['validationRules'];
57
                }
58
                // add validation rules for subfields
59
                if (array_key_exists('subfields', $item)) {
60
                    $subfieldsWithValidation = array_filter($item['subfields'], function ($subfield) {
61
                        return array_key_exists('validationRules', $subfield);
62
                    });
63
64
                    foreach ($subfieldsWithValidation as $subfield) {
65
                        $validationRules[$item['name'].'.*.'.$subfield['name']] = $subfield['validationRules'];
66
                    }
67
                }
68
69
                return $validationRules;
70
            })->toArray();
71
72
        return array_merge(...array_values($rules));
73
    }
74
75
    /**
76
     * Return the messages for the fields and subfields in the current crud panel.
77
     *
78
     * @param  array  $fields
79
     * @return array
80
     */
81
    private function getValidationMessagesFromFieldsAndSubfields($fields)
82
    {
83
        $messages = [];
84
        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

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

85
            ->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...
86
                // only keep fields where 'validationMessages' OR there are subfields
87
                return array_key_exists('validationMessages', $value) || array_key_exists('subfields', $value);
88
            })->each(function ($item, $key) use (&$messages) {
89
                if (isset($item['validationMessages'])) {
90
                    foreach ($item['validationMessages'] as $rule => $message) {
91
                        $messages[$key.'.'.$rule] = $message;
92
                    }
93
                }
94
                // add messages from subfields
95
                if (array_key_exists('subfields', $item)) {
96
                    $subfieldsWithValidationMessages = array_filter($item['subfields'], function ($subfield) {
97
                        return array_key_exists('validationRules', $subfield);
98
                    });
99
100
                    foreach ($subfieldsWithValidationMessages as $subfield) {
101
                        foreach ($subfield['validationMessages'] as $rule => $message) {
102
                            $messages[$item['name'].'.*.'.$subfield['name'].'.'.$rule] = $message;
103
                        }
104
                    }
105
                }
106
            })->toArray();
107
108
        return $messages;
109
    }
110
111
    /**
112
     * Mark a FormRequest file as required for the current operation, in Settings.
113
     * Adds the required rules to an array for easy access.
114
     *
115
     * @param  string  $class  Class that extends FormRequest
116
     */
117
    public function setValidationFromRequest($class)
118
    {
119
        $this->setFormRequest($class);
120
        $this->setRequiredFields($class);
121
    }
122
123
    /**
124
     * Mark a FormRequest file as required for the current operation, in Settings.
125
     * Adds the required rules to an array for easy access.
126
     *
127
     * @param  string|array  $classOrRulesArray  Class that extends FormRequest or array of validation rules
128
     * @param  array  $messages  Array of validation messages.
129
     */
130
    public function setValidation($classOrRulesArray = false, $messages = [])
131
    {
132
        if (! $classOrRulesArray) {
133
            $this->setValidationFromFields();
134
        } elseif (is_array($classOrRulesArray)) {
135
            $this->setValidationFromArray($classOrRulesArray, $messages);
136
        } elseif (is_string($classOrRulesArray) || class_exists($classOrRulesArray)) {
0 ignored issues
show
introduced by
The condition is_string($classOrRulesArray) is always true.
Loading history...
137
            $this->setValidationFromRequest($classOrRulesArray);
138
        } else {
139
            abort(500, 'Please pass setValidation() nothing, a rules array or a FormRequest class.');
140
        }
141
    }
142
143
    /**
144
     * Remove the current FormRequest from configuration, so it will no longer be validated.
145
     */
146
    public function unsetValidation()
147
    {
148
        $this->setOperationSetting('formRequest', false);
149
        $this->setOperationSetting('validationRules', []);
150
        $this->setOperationSetting('validationMessages', []);
151
        $this->setOperationSetting('requiredFields', []);
152
    }
153
154
    /**
155
     * Remove the current FormRequest from configuration, so it will no longer be validated.
156
     */
157
    public function disableValidation()
158
    {
159
        $this->unsetValidation();
160
    }
161
162
    /**
163
     * Mark a FormRequest file as required for the current operation, in Settings.
164
     *
165
     * @param  string  $class  Class that extends FormRequest
166
     */
167
    public function setFormRequest($class)
168
    {
169
        $this->setOperationSetting('formRequest', $class);
170
    }
171
172
    /**
173
     * Get the current form request file, in any.
174
     * Returns null if no FormRequest is required for the current operation.
175
     *
176
     * @return string Class that extends FormRequest
177
     */
178
    public function getFormRequest()
179
    {
180
        return $this->getOperationSetting('formRequest');
181
    }
182
183
    /**
184
     * Run the authorization and validation for the current crud panel.
185
     * That authorization is gathered from 3 places:
186
     * - the FormRequest when provided.
187
     * - the rules added in the controller.
188
     * - the rules defined in the fields itself.
189
     *
190
     * @return \Illuminate\Http\Request
191
     */
192
    public function validateRequest()
193
    {
194
        $formRequest = $this->getFormRequest();
195
196
        $rules = $this->getOperationSetting('validationRules') ?? [];
197
        $messages = $this->getOperationSetting('validationMessages') ?? [];
198
199
        if ($formRequest) {
200
            // when there is no validation in the fields, just validate the form request.
201
            if (empty($rules)) {
202
                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...
203
            }
204
205
            $formRequest = (new $formRequest)->createFrom($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

205
            $formRequest = (new $formRequest)->createFrom($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...
206
            $extendedRules = $this->mergeRules($formRequest, $rules);
207
            $extendedMessages = array_merge($messages, $formRequest->messages());
208
209
            // validate the complete request with FormRequest + controller validation + field validation (our anonymous class)
210
            return $this->checkRequestValidity($extendedRules, $extendedMessages, $formRequest);
211
        }
212
213
        return ! empty($rules) ? $this->checkRequestValidity($rules, $messages) : $this->getRequest();
214
    }
215
216
    /**
217
     * Return an array containing the request rules and the field/controller rules merged.
218
     * The rules in request will take precedence over the ones in controller/fields.
219
     *
220
     * @param  \Illuminate\Http\Request  $request
221
     * @param  array  $rules
222
     * @return array
223
     */
224
    private function mergeRules($request, $rules)
225
    {
226
        $extendedRules = [];
227
        $requestRules = $this->getRequestRulesAsArray($request);
228
        $rules = array_map(function ($ruleDefinition) {
229
            return is_array($ruleDefinition) ? $ruleDefinition : explode('|', $ruleDefinition);
230
        }, $rules);
231
232
        foreach ($requestRules as $ruleKey => $rule) {
233
            $extendedRules[$ruleKey] = array_key_exists($ruleKey, $rules) ? array_merge($rule, $rules[$ruleKey]) : $rule;
234
            unset($rules[$ruleKey]);
235
        }
236
237
        return array_merge($rules, $extendedRules);
238
    }
239
240
    /**
241
     * Return the request rules as an array of rules if developer provided a rule string configuration.
242
     *
243
     * @param  \Illuminate\Http\Request  $request
244
     * @return array
245
     */
246
    private function getRequestRulesAsArray($request)
247
    {
248
        $requestRules = [];
249
        foreach ($request->rules() as $ruleKey => $rule) {
250
            $requestRules[$ruleKey] = is_array($rule) ? $rule : explode('|', $rule);
251
        }
252
253
        return $requestRules;
254
    }
255
256
    /**
257
     * Checks if the request is valid against the rules.
258
     *
259
     * @param  array  $rules
260
     * @param  array  $messages
261
     * @param  \Illuminate\Http\Request|null  $request
262
     * @return \Illuminate\Http\Request
263
     */
264
    private function checkRequestValidity($rules, $messages, $request = null)
265
    {
266
        $request = $request ?? $this->getRequest();
267
        $request->validate($rules, $messages);
268
269
        return $request;
270
    }
271
272
    /**
273
     * Parse a FormRequest class, figure out what inputs are required
274
     * and store this knowledge in the current object.
275
     *
276
     * @param  string|array  $classOrRulesArray  Class that extends FormRequest or rules array
277
     */
278
    public function setRequiredFields($classOrRulesArray)
279
    {
280
        $requiredFields = $this->getOperationSetting('requiredFields') ?? [];
281
282
        if (is_array($classOrRulesArray)) {
283
            $rules = $classOrRulesArray;
284
        } else {
285
            $formRequest = new $classOrRulesArray();
286
            $rules = $formRequest->rules();
287
        }
288
289
        if (count($rules)) {
290
            foreach ($rules as $key => $rule) {
291
                if (
292
                    (is_string($rule) && strpos($rule, 'required') !== false && strpos($rule, 'required_') === false) ||
293
                    (is_array($rule) && array_search('required', $rule) !== false && array_search('required_', $rule) === false)
294
                ) {
295
                    if (Str::contains($key, '.')) {
296
                        $key = Str::dotsToSquareBrackets($key, ['*']);
297
                    }
298
299
                    $requiredFields[] = $key;
300
                }
301
            }
302
        }
303
304
        // merge any previous required fields with current ones
305
        $requiredFields = array_merge($this->getOperationSetting('requiredFields') ?? [], $requiredFields);
306
307
        // since this COULD BE called twice (to support the previous syntax where developers needed to call `setValidation` after the field definition)
308
        // 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
309
        // no sense in doing it, so array_unique() it is.
310
        $requiredFields = array_unique($requiredFields);
311
312
        $this->setOperationSetting('requiredFields', $requiredFields);
313
    }
314
315
    /**
316
     * Check the current object to see if an input is required
317
     * for the given operation.
318
     *
319
     * @param  string  $inputKey  Field or input name.
320
     * @param  string  $operation  create / update
321
     * @return bool
322
     */
323
    public function isRequired($inputKey)
324
    {
325
        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

325
        if (! $this->/** @scrutinizer ignore-call */ hasOperationSetting('requiredFields')) {
Loading history...
326
            return false;
327
        }
328
329
        if (Str::contains($inputKey, '.')) {
330
            $inputKey = Str::dotsToSquareBrackets($inputKey, ['*']);
331
        }
332
333
        return in_array($inputKey, $this->getOperationSetting('requiredFields'));
334
    }
335
336
    /**
337
     * Add the validation setup by developer in field `validationRules` to the crud validation.
338
     *
339
     * @param  array  $field  - the field we want to get the validation from.
340
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
341
     */
342
    private function setupFieldValidation($field, $parent = false)
343
    {
344
        [$rules, $messages] = $this->getValidationRulesAndMessagesFromField($field, $parent);
345
346
        if (! empty($rules)) {
347
            $this->setValidation($rules, $messages);
348
        }
349
    }
350
351
    /**
352
     * Return the array of rules and messages with the validation key accordingly set
353
     * to match the field or the subfield accordingly.
354
     *
355
     * @param  array  $field  - the field we want to get the rules and messages from.
356
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
357
     */
358
    private function getValidationRulesAndMessagesFromField($field, $parent = false)
359
    {
360
        $rules = [];
361
        $messages = [];
362
363
        foreach ((array) $field['name'] as $fieldName) {
364
            if ($parent) {
365
                $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

365
                $fieldName = /** @scrutinizer ignore-type */ $parent.'.*.'.$fieldName;
Loading history...
366
            }
367
368
            if (isset($field['validationRules'])) {
369
                $rules[$fieldName] = $field['validationRules'];
370
            }
371
            if (isset($field['validationMessages'])) {
372
                foreach ($field['validationMessages'] as $validator => $message) {
373
                    $fieldValidationName = $fieldName.'.'.$validator;
374
                    $messages[$fieldValidationName] = $message;
375
                }
376
            }
377
        }
378
379
        return [$rules, $messages];
380
    }
381
}
382