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 — poc-backpack-components ( 997beb...192cbc )
by Pedro
15:02
created

Validation.php$0 ➔ isRequired()   A

Complexity

Conditions 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
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) {
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) {
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) || is_class($classOrRulesArray)) {
0 ignored issues
show
introduced by
The condition is_string($classOrRulesArray) is always true.
Loading history...
Bug introduced by
The function is_class was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

136
        } elseif (is_string($classOrRulesArray) || /** @scrutinizer ignore-call */ is_class($classOrRulesArray)) {
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
            // create an alias of the provided FormRequest so we can create a new class that extends it.
206
            // we can't use $variables to extend classes.
207
            class_alias(get_class(new $formRequest), 'DeveloperProvidedFormRequest');
208
209
            // create a new anonymous class that will extend the provided developer FormRequest
210
            // in this class we will merge the FormRequest rules() and messages() with the ones provided by developer in fields.
211
            $extendedRequest = new class($rules, $messages) extends \DeveloperProvidedFormRequest
0 ignored issues
show
Bug introduced by
The type DeveloperProvidedFormRequest 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...
212
            {
213
                private $_rules;
214
215
                private $_messages;
216
217
                public function __construct($rules, $messages)
218
                {
219
                    parent::__construct();
220
                    $this->_rules = $rules;
221
                    $this->_messages = $messages;
222
                }
223
224
                public function rules()
225
                {
226
                    return array_merge(parent::rules(), $this->_rules);
227
                }
228
229
                public function messages()
230
                {
231
                    return array_merge(parent::messages(), $this->_messages);
232
                }
233
            };
234
235
            // validate the complete request with FormRequest + controller validation + field validation (our anonymous class)
236
            return app(get_class($extendedRequest), ['rules' => $rules, 'messages' => $messages]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return app(get_class($ex...essages' => $messages)) also could return the type Illuminate\Contracts\Foundation\Application which is incompatible with the documented return type Illuminate\Http\Request.
Loading history...
237
        }
238
239
        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 getFormRequest()? ( Ignorable by Annotation )

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

239
        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...
240
    }
241
242
    /**
243
     * Checks if the current crud request is valid against the provided rules.
244
     *
245
     * @param  array  $rules
246
     * @param  array  $messages
247
     * @return \Illuminate\Http\Request
248
     */
249
    private function checkRequestValidity($rules, $messages)
250
    {
251
        $this->getRequest()->validate($rules, $messages);
252
253
        return $this->getRequest();
254
    }
255
256
    /**
257
     * Parse a FormRequest class, figure out what inputs are required
258
     * and store this knowledge in the current object.
259
     *
260
     * @param  string|array  $classOrRulesArray  Class that extends FormRequest or rules array
261
     */
262
    public function setRequiredFields($classOrRulesArray)
263
    {
264
        $requiredFields = $this->getOperationSetting('requiredFields') ?? [];
265
266
        if (is_array($classOrRulesArray)) {
267
            $rules = $classOrRulesArray;
268
        } else {
269
            $formRequest = new $classOrRulesArray();
270
            $rules = $formRequest->rules();
271
        }
272
273
        if (count($rules)) {
274
            foreach ($rules as $key => $rule) {
275
                if (
276
                    (is_string($rule) && strpos($rule, 'required') !== false && strpos($rule, 'required_') === false) ||
277
                    (is_array($rule) && array_search('required', $rule) !== false && array_search('required_', $rule) === false)
278
                ) {
279
                    if (Str::contains($key, '.')) {
280
                        $key = Str::dotsToSquareBrackets($key, ['*']);
281
                    }
282
283
                    $requiredFields[] = $key;
284
                }
285
            }
286
        }
287
288
        // merge any previous required fields with current ones
289
        $requiredFields = array_merge($this->getOperationSetting('requiredFields') ?? [], $requiredFields);
290
291
        // since this COULD BE called twice (to support the previous syntax where developers needed to call `setValidation` after the field definition)
292
        // 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
293
        // no sense in doing it, so array_unique() it is.
294
        $requiredFields = array_unique($requiredFields);
295
296
        $this->setOperationSetting('requiredFields', $requiredFields);
297
    }
298
299
    /**
300
     * Check the current object to see if an input is required
301
     * for the given operation.
302
     *
303
     * @param  string  $inputKey  Field or input name.
304
     * @param  string  $operation  create / update
305
     * @return bool
306
     */
307
    public function isRequired($inputKey)
308
    {
309
        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

309
        if (! $this->/** @scrutinizer ignore-call */ hasOperationSetting('requiredFields')) {
Loading history...
310
            return false;
311
        }
312
313
        if (Str::contains($inputKey, '.')) {
314
            $inputKey = Str::dotsToSquareBrackets($inputKey, ['*']);
315
        }
316
317
        return in_array($inputKey, $this->getOperationSetting('requiredFields'));
318
    }
319
320
    /**
321
     * Add the validation setup by developer in field `validationRules` to the crud validation.
322
     *
323
     * @param  array  $field  - the field we want to get the validation from.
324
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
325
     */
326
    private function setupFieldValidation($field, $parent = false)
327
    {
328
        [$rules, $messages] = $this->getValidationRulesAndMessagesFromField($field, $parent);
329
330
        if (! empty($rules)) {
331
            $this->setValidation($rules, $messages);
332
        }
333
    }
334
335
    /**
336
     * Return the array of rules and messages with the validation key accordingly set
337
     * to match the field or the subfield accordingly.
338
     *
339
     * @param  array  $field  - the field we want to get the rules and messages from.
340
     * @param  bool|string  $parent  - the parent name when setting up validation for subfields.
341
     */
342
    private function getValidationRulesAndMessagesFromField($field, $parent = false)
343
    {
344
        $rules = [];
345
        $messages = [];
346
347
        foreach ((array) $field['name'] as $fieldName) {
348
            if ($parent) {
349
                $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

349
                $fieldName = /** @scrutinizer ignore-type */ $parent.'.*.'.$fieldName;
Loading history...
350
            }
351
352
            if (isset($field['validationRules'])) {
353
                $rules[$fieldName] = $field['validationRules'];
354
            }
355
            if (isset($field['validationMessages'])) {
356
                foreach ($field['validationMessages'] as $validator => $message) {
357
                    $fieldValidationName = $fieldName.'.'.$validator;
358
                    $messages[$fieldValidationName] = $message;
359
                }
360
            }
361
        }
362
363
        return [$rules, $messages];
364
    }
365
}
366