|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Longman\LaravelLodash\Http\Requests; |
|
6
|
|
|
|
|
7
|
|
|
use Illuminate\Support\Arr; |
|
8
|
|
|
use Illuminate\Validation\ValidationException; |
|
9
|
|
|
|
|
10
|
|
|
use function __; |
|
11
|
|
|
use function app; |
|
12
|
|
|
use function array_diff; |
|
13
|
|
|
use function array_keys; |
|
14
|
|
|
use function config; |
|
15
|
|
|
use function method_exists; |
|
16
|
|
|
use function preg_replace; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @mixin \Illuminate\Foundation\Http\FormRequest |
|
20
|
|
|
*/ |
|
21
|
|
|
trait RestrictsExtraAttributes |
|
22
|
|
|
{ |
|
23
|
4 |
|
protected function prepareForValidation(): void |
|
24
|
|
|
{ |
|
25
|
4 |
|
$this->checkForNotAllowedProperties(); |
|
26
|
|
|
|
|
27
|
|
|
parent::prepareForValidation(); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
4 |
|
private function checkForNotAllowedProperties(): void |
|
31
|
|
|
{ |
|
32
|
4 |
|
$extraAttributes = array_diff( |
|
33
|
4 |
|
$this->getValidationData(), |
|
34
|
4 |
|
$this->getAllowedAttributes(), |
|
35
|
|
|
); |
|
|
|
|
|
|
36
|
|
|
|
|
37
|
4 |
|
if (! empty($extraAttributes)) { |
|
38
|
4 |
|
$messages = []; |
|
39
|
4 |
|
foreach ($extraAttributes as $attribute) { |
|
40
|
4 |
|
$message = __('validation.restrict_extra_attributes', ['attribute' => $attribute]); |
|
41
|
4 |
|
if (config('app.debug')) { |
|
42
|
|
|
$message .= ' Request Class: ' . static::class; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
$messages[] = $message; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
4 |
|
throw ValidationException::withMessages($messages); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
4 |
|
private function getValidationData(): array |
|
53
|
|
|
{ |
|
54
|
4 |
|
$data = Arr::dot($this->validationData()); |
|
55
|
|
|
|
|
56
|
4 |
|
$return = []; |
|
57
|
4 |
|
foreach ($data as $key => $value) { |
|
58
|
4 |
|
$key = preg_replace('#\.\d+#', '.*', $key); |
|
59
|
4 |
|
$return[] = $key; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
4 |
|
return $return; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
4 |
|
private function getAllowedAttributes(): array |
|
66
|
|
|
{ |
|
67
|
4 |
|
if (method_exists($this, 'possibleAttributes')) { |
|
68
|
|
|
return $this->possibleAttributes(); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
4 |
|
$rules = app()->call([$this, 'rules']); |
|
72
|
|
|
|
|
73
|
4 |
|
return array_keys($rules); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|