We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
Total Complexity | 75 |
Total Lines | 483 |
Duplicated Lines | 0 % |
Changes | 0 |
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 |
||
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)); |
||
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); |
||
142 | } |
||
143 | |||
144 | [$formRequest, $extendedRules, $extendedMessages, $extendedAttributes] = $this->mergeRequestAndFieldRules($formRequest, $rules, $messages, $attributes); |
||
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(); |
||
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 | $key = $this->checkIfRuleIsRequired($key, $customValidatorRules); |
||
205 | if ($key) { |
||
206 | $requiredFields[] = $key; |
||
207 | } |
||
208 | } |
||
209 | |||
210 | continue; |
||
211 | } |
||
212 | $key = $this->checkIfRuleIsRequired($key, $rule); |
||
213 | if ($key) { |
||
214 | $requiredFields[] = $key; |
||
215 | } |
||
216 | } |
||
217 | } |
||
218 | } |
||
219 | |||
220 | // merge any previous required fields with current ones |
||
221 | $requiredFields = array_merge($this->getOperationSetting('requiredFields') ?? [], $requiredFields); |
||
222 | |||
223 | // since this COULD BE called twice (to support the previous syntax where developers needed to call `setValidation` after the field definition) |
||
224 | // 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 |
||
225 | // no sense in doing it, so array_unique() it is. |
||
226 | $requiredFields = array_unique($requiredFields); |
||
227 | |||
228 | $this->setOperationSetting('requiredFields', $requiredFields); |
||
229 | } |
||
230 | |||
231 | /** |
||
232 | * Check the current object to see if an input is required |
||
233 | * for the given operation. |
||
234 | * |
||
235 | * @param string $inputKey Field or input name. |
||
236 | * @param string $operation create / update |
||
237 | * @return bool |
||
238 | */ |
||
239 | public function isRequired($inputKey) |
||
240 | { |
||
241 | if (! $this->hasOperationSetting('requiredFields')) { |
||
242 | return false; |
||
243 | } |
||
244 | |||
245 | if (Str::contains($inputKey, '.')) { |
||
246 | $inputKey = Str::dotsToSquareBrackets($inputKey, ['*']); |
||
247 | } |
||
248 | |||
249 | return in_array($inputKey, $this->getOperationSetting('requiredFields')); |
||
250 | } |
||
251 | |||
252 | /** |
||
253 | * Add the validation setup by developer in field `validationRules` to the crud validation. |
||
254 | * |
||
255 | * @param array $field - the field we want to get the validation from. |
||
256 | * @param bool|string $parent - the parent name when setting up validation for subfields. |
||
257 | */ |
||
258 | private function setupFieldValidation($field, $parent = false) |
||
259 | { |
||
260 | [$rules, $messages, $attributes] = $this->getValidationDataFromField($field, $parent); |
||
261 | |||
262 | if (! empty($rules)) { |
||
263 | $this->setValidation($rules, $messages, $attributes); |
||
264 | } |
||
265 | } |
||
266 | |||
267 | /** |
||
268 | * Return the messages for the fields and subfields in the current crud panel. |
||
269 | * |
||
270 | * @param array $fields |
||
271 | * @return array |
||
272 | */ |
||
273 | private function getValidationMessagesFromFieldsAndSubfields($fields) |
||
274 | { |
||
275 | $messages = []; |
||
276 | collect($fields) |
||
277 | ->filter(function ($value, $key) { |
||
278 | // only keep fields where 'validationMessages' OR there are subfields |
||
279 | return array_key_exists('validationMessages', $value) || array_key_exists('subfields', $value); |
||
280 | })->each(function ($item, $key) use (&$messages) { |
||
281 | if (isset($item['validationMessages'])) { |
||
282 | foreach ($item['validationMessages'] as $rule => $message) { |
||
283 | $messages[$key.'.'.$rule] = $message; |
||
284 | } |
||
285 | } |
||
286 | // add messages from subfields |
||
287 | if (array_key_exists('subfields', $item)) { |
||
288 | $subfieldsWithValidationMessages = array_filter($item['subfields'], function ($subfield) { |
||
289 | return array_key_exists('validationRules', $subfield); |
||
290 | }); |
||
291 | |||
292 | foreach ($subfieldsWithValidationMessages as $subfield) { |
||
293 | foreach ($subfield['validationMessages'] ?? [] as $rule => $message) { |
||
294 | $messages[$item['name'].'.*.'.$subfield['name'].'.'.$rule] = $message; |
||
295 | } |
||
296 | } |
||
297 | } |
||
298 | })->toArray(); |
||
299 | |||
300 | return $messages; |
||
301 | } |
||
302 | |||
303 | /** |
||
304 | * Return the attributes for the fields and subfields in the current crud panel. |
||
305 | * |
||
306 | * @param array $fields |
||
307 | * @return array |
||
308 | */ |
||
309 | private function getValidationAttributesFromFieldsAndSubfields($fields) |
||
310 | { |
||
311 | $attributes = []; |
||
312 | collect($fields) |
||
313 | ->filter(function ($value, $key) { |
||
314 | // only keep fields where 'validationAttribute' exists OR there are subfields |
||
315 | return array_key_exists('validationAttribute', $value) || array_key_exists('subfields', $value); |
||
316 | })->each(function ($item, $key) use (&$attributes) { |
||
317 | if (isset($item['validationAttribute'])) { |
||
318 | $attributes[$key] = $item['validationAttribute']; |
||
319 | } |
||
320 | // add attributes from subfields |
||
321 | if (array_key_exists('subfields', $item)) { |
||
322 | $subfieldsWithValidationAttribute = array_filter($item['subfields'], function ($subfield) { |
||
323 | return array_key_exists('validationAttribute', $subfield); |
||
324 | }); |
||
325 | |||
326 | foreach ($subfieldsWithValidationAttribute as $subfield) { |
||
327 | $attributes[$item['name'].'.*.'.$subfield['name']] = $subfield['validationAttribute']; |
||
328 | } |
||
329 | } |
||
330 | })->toArray(); |
||
331 | |||
332 | return $attributes; |
||
333 | } |
||
334 | |||
335 | /** |
||
336 | * Return the rules for the fields and subfields in the current crud panel. |
||
337 | * |
||
338 | * @param array $fields |
||
339 | * @return array |
||
340 | */ |
||
341 | private function getValidationRulesFromFieldsAndSubfields($fields) |
||
342 | { |
||
343 | $rules = collect($fields) |
||
344 | ->filter(function ($value, $key) { |
||
345 | // only keep fields where 'validationRules' OR there are subfields |
||
346 | return array_key_exists('validationRules', $value) || array_key_exists('subfields', $value); |
||
347 | })->map(function ($item, $key) { |
||
348 | $validationRules = []; |
||
349 | // only keep the rules, not the entire field definition |
||
350 | if (isset($item['validationRules'])) { |
||
351 | $validationRules[$key] = $item['validationRules']; |
||
352 | } |
||
353 | // add validation rules for subfields |
||
354 | if (array_key_exists('subfields', $item)) { |
||
355 | $subfieldsWithValidation = array_filter($item['subfields'], function ($subfield) { |
||
356 | return array_key_exists('validationRules', $subfield); |
||
357 | }); |
||
358 | |||
359 | foreach ($subfieldsWithValidation as $subfield) { |
||
360 | $validationRules[$item['name'].'.*.'.$subfield['name']] = $subfield['validationRules']; |
||
361 | } |
||
362 | } |
||
363 | |||
364 | return $validationRules; |
||
365 | })->toArray(); |
||
366 | |||
367 | return array_merge(...array_values($rules)); |
||
368 | } |
||
369 | |||
370 | /** |
||
371 | * Return the array of rules and messages with the validation key accordingly set |
||
372 | * to match the field or the subfield accordingly. |
||
373 | * |
||
374 | * @param array $field - the field we want to get the rules and messages from. |
||
375 | * @param bool|string $parent - the parent name when setting up validation for subfields. |
||
376 | */ |
||
377 | private function getValidationDataFromField($field, $parent = false) |
||
378 | { |
||
379 | $rules = []; |
||
380 | $messages = []; |
||
381 | $attributes = []; |
||
382 | |||
383 | foreach ((array) $field['name'] as $fieldName) { |
||
384 | if ($parent) { |
||
385 | $fieldName = $parent.'.*.'.$fieldName; |
||
386 | } |
||
387 | |||
388 | if (isset($field['validationRules'])) { |
||
389 | $rules[$fieldName] = $field['validationRules']; |
||
390 | } |
||
391 | if (isset($field['validationMessages'])) { |
||
392 | foreach ($field['validationMessages'] as $validator => $message) { |
||
393 | $messages[$fieldName.'.'.$validator] = $message; |
||
394 | } |
||
395 | } |
||
396 | if (isset($field['validationAttribute'])) { |
||
397 | $attributes[$fieldName] = $field['validationAttribute']; |
||
398 | } |
||
399 | } |
||
400 | |||
401 | return [$rules, $messages, $attributes]; |
||
402 | } |
||
403 | |||
404 | /** |
||
405 | * Return an array containing the request rules and the field/controller rules merged. |
||
406 | * The rules in request will take precedence over the ones in controller/fields. |
||
407 | * |
||
408 | * @param \Illuminate\Http\Request $request |
||
409 | * @param array $rules |
||
410 | * @return array |
||
411 | */ |
||
412 | private function mergeRules($request, $rules) |
||
413 | { |
||
414 | $extendedRules = []; |
||
415 | $requestRules = $this->getRequestRulesAsArray($request); |
||
416 | |||
417 | $rules = $this->getRulesAsArray($rules); |
||
418 | |||
419 | foreach ($requestRules as $ruleKey => $rule) { |
||
420 | $extendedRules[$ruleKey] = array_key_exists($ruleKey, $rules) ? array_merge($rule, $this->getRulesAsArray($rules[$ruleKey])) : $rule; |
||
421 | unset($rules[$ruleKey]); |
||
422 | } |
||
423 | |||
424 | return array_merge($rules, $extendedRules); |
||
425 | } |
||
426 | |||
427 | /** |
||
428 | * Return the request rules as an array of rules if developer provided a rule string configuration. |
||
429 | * |
||
430 | * @param \Illuminate\Http\Request $request |
||
431 | * @return array |
||
432 | */ |
||
433 | private function getRequestRulesAsArray($request) |
||
434 | { |
||
435 | $requestRules = []; |
||
436 | foreach ($request->rules() as $ruleKey => $rule) { |
||
437 | $requestRules[$ruleKey] = $this->getRulesAsArray($rule); |
||
438 | } |
||
439 | |||
440 | return $requestRules; |
||
441 | } |
||
442 | |||
443 | /** |
||
444 | * Checks if the request is valid against the rules. |
||
445 | * |
||
446 | * @param array $rules |
||
447 | * @param array $messages |
||
448 | * @param \Illuminate\Http\Request|null $request |
||
449 | * @return \Illuminate\Http\Request |
||
450 | */ |
||
451 | private function checkRequestValidity($rules, $messages, $attributes, $request = null) |
||
452 | { |
||
453 | $request = $request ?? $this->getRequest(); |
||
454 | $request->validate($rules, $messages, $attributes); |
||
455 | |||
456 | return $request; |
||
457 | } |
||
458 | |||
459 | /** |
||
460 | * Check if the given rule is a required rule. |
||
461 | * |
||
462 | * @param string $key |
||
463 | * @param string $rule |
||
464 | * @return string|bool |
||
465 | */ |
||
466 | private function checkIfRuleIsRequired($key, $rule) |
||
467 | { |
||
468 | if ( |
||
469 | (is_string($rule) && strpos($rule, 'required') !== false && strpos($rule, 'required_') === false) || |
||
470 | (is_array($rule) && array_search('required', $rule) !== false && array_search('required_', $rule) === false) |
||
471 | ) { |
||
472 | if (Str::contains($key, '.')) { |
||
473 | $key = Str::dotsToSquareBrackets($key, ['*']); |
||
474 | } |
||
475 | |||
476 | return $key; |
||
477 | } |
||
478 | |||
479 | return false; |
||
480 | } |
||
481 | |||
482 | /** |
||
483 | * Prepare the rules as array. |
||
484 | */ |
||
485 | private function getRulesAsArray($rules) |
||
492 | } |
||
493 | } |
||
494 |