forked from laravel/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormRequest.php
More file actions
432 lines (367 loc) · 10.9 KB
/
FormRequest.php
File metadata and controls
432 lines (367 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php
namespace Illuminate\Foundation\Http;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\Access\Response;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Contracts\Validation\ValidatesWhenResolved;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\Attributes\ErrorBag;
use Illuminate\Foundation\Http\Attributes\FailOnUnknownFields;
use Illuminate\Foundation\Http\Attributes\RedirectTo;
use Illuminate\Foundation\Http\Attributes\RedirectToRoute;
use Illuminate\Foundation\Http\Attributes\StopOnFirstFailure;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Arr;
use Illuminate\Validation\ValidatesWhenResolvedTrait;
use ReflectionClass;
class FormRequest extends Request implements ValidatesWhenResolved
{
use ValidatesWhenResolvedTrait;
/**
* The container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The redirector instance.
*
* @var \Illuminate\Routing\Redirector
*/
protected $redirector;
/**
* The URI to redirect to if validation fails.
*
* @var string
*/
protected $redirect;
/**
* The route to redirect to if validation fails.
*
* @var string
*/
protected $redirectRoute;
/**
* The controller action to redirect to if validation fails.
*
* @var string
*/
protected $redirectAction;
/**
* The key to be used for the view error bag.
*
* @var string
*/
protected $errorBag = 'default';
/**
* Indicates whether validation should stop after the first rule failure.
*
* @var bool
*/
protected $stopOnFirstFailure = false;
/**
* The validator instance.
*
* @var \Illuminate\Contracts\Validation\Validator
*/
protected $validator;
/**
* Indicates if unknown fields should be rejected for all form requests.
*
* @var bool
*/
protected static bool $globalFailOnUnknownFields = false;
/**
* Get the validator instance for the request.
*
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function getValidatorInstance()
{
if ($this->validator) {
return $this->validator;
}
$this->configureFromAttributes();
$factory = $this->container->make(ValidationFactory::class);
if (method_exists($this, 'validator')) {
$validator = $this->container->call($this->validator(...), compact('factory'));
} else {
$validator = $this->createDefaultValidator($factory);
}
if (method_exists($this, 'withValidator')) {
$this->withValidator($validator);
}
if (method_exists($this, 'after')) {
$validator->after($this->container->call(
$this->after(...),
['validator' => $validator]
));
}
if ($this->shouldFailOnUnknownFields()) {
$validator->after(function (Validator $validator) {
$this->validateNoUnknownFields($validator);
});
}
$this->setValidator($validator);
return $this->validator;
}
/**
* Configure the form request from class attributes.
*
* @return void
*/
protected function configureFromAttributes()
{
$reflection = new ReflectionClass($this);
if (count($reflection->getAttributes(StopOnFirstFailure::class)) > 0) {
$this->stopOnFirstFailure = true;
}
$redirectTo = $reflection->getAttributes(RedirectTo::class);
if (count($redirectTo) > 0) {
$this->redirect = $redirectTo[0]->newInstance()->url;
}
$redirectToRoute = $reflection->getAttributes(RedirectToRoute::class);
if (count($redirectToRoute) > 0) {
$this->redirectRoute = $redirectToRoute[0]->newInstance()->route;
}
$errorBag = $reflection->getAttributes(ErrorBag::class);
if (count($errorBag) > 0) {
$this->errorBag = $errorBag[0]->newInstance()->name;
}
}
/**
* Create the default validator instance.
*
* @param \Illuminate\Contracts\Validation\Factory $factory
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function createDefaultValidator(ValidationFactory $factory)
{
$rules = $this->validationRules();
$validator = $factory->make(
$this->validationData(),
$rules,
$this->messages(),
$this->attributes(),
)->stopOnFirstFailure($this->stopOnFirstFailure);
if ($this->isPrecognitive()) {
$validator->setRules(
$this->filterPrecognitiveRules($validator->getRulesWithoutPlaceholders())
);
}
return $validator;
}
/**
* Get data to be validated from the request.
*
* @return array
*/
public function validationData()
{
return $this->all();
}
/**
* Get the validation rules for this form request.
*
* @return array
*/
protected function validationRules()
{
return method_exists($this, 'rules') ? $this->container->call([$this, 'rules']) : [];
}
/**
* Determine if fields not present in rules should fail validation.
*
* @return bool
*/
protected function shouldFailOnUnknownFields(): bool
{
$failOnUnknownFields = (new ReflectionClass($this))->getAttributes(FailOnUnknownFields::class);
return $failOnUnknownFields !== []
? $failOnUnknownFields[0]->newInstance()->value
: static::$globalFailOnUnknownFields;
}
/**
* Validate that no unknown fields were sent as input.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
protected function validateNoUnknownFields(Validator $validator): void
{
$allowedKeys = array_keys($this->validationRules());
foreach (array_keys(Arr::dot($this->all())) as $inputKey) {
if (! $this->isKnownField($inputKey, $allowedKeys)) {
$validator->errors()->add($inputKey, trans('validation.prohibited', [
'attribute' => str_replace('_', ' ', $inputKey),
]));
}
}
}
/**
* Determine if the given input key is an allowed key based on the validation rules.
*
* @param string $inputKey
* @param array $allowedKeys
* @return bool
*/
protected function isKnownField(string $inputKey, array $allowedKeys): bool
{
foreach ($allowedKeys as $ruleKey) {
if ($ruleKey === $inputKey) {
return true;
}
if (str_contains($ruleKey, '*')) {
$pattern = '/^'.str_replace('\*', '[^.]+', preg_quote($ruleKey, '/')).'$/';
if (preg_match($pattern, $inputKey)) {
return true;
}
}
}
return false;
}
/**
* Handle a failed validation attempt.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function failedValidation(Validator $validator)
{
$exception = $validator->getException();
throw (new $exception($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());
}
/**
* Get the URL to redirect to on a validation error.
*
* @return string
*/
protected function getRedirectUrl()
{
$url = $this->redirector->getUrlGenerator();
if ($this->redirect) {
return $url->to($this->redirect);
} elseif ($this->redirectRoute) {
return $url->route($this->redirectRoute);
} elseif ($this->redirectAction) {
return $url->action($this->redirectAction);
}
return $url->previous();
}
/**
* Determine if the request passes the authorization check.
*
* @return bool
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function passesAuthorization()
{
if (method_exists($this, 'authorize')) {
$result = $this->container->call([$this, 'authorize']);
return $result instanceof Response ? $result->authorize() : $result;
}
return true;
}
/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
throw new AuthorizationException;
}
/**
* Get a validated input container for the validated input.
*
* @param array|null $keys
* @return \Illuminate\Support\ValidatedInput|array
*/
public function safe(?array $keys = null)
{
return is_array($keys)
? $this->validator->safe()->only($keys)
: $this->validator->safe();
}
/**
* Get the validated data from the request.
*
* @param array|int|string|null $key
* @param mixed $default
* @return mixed
*/
public function validated($key = null, $default = null)
{
return data_get($this->validator->validated(), $key, $default);
}
/**
* Get custom messages for validator errors.
*
* @return array<string, string>
*/
public function messages()
{
return [];
}
/**
* Get custom attributes for validator errors.
*
* @return array<string, string>
*/
public function attributes()
{
return [];
}
/**
* Enable or disable unknown-field rejection globally for all form requests.
*
* @param bool $value
* @return void
*/
public static function failOnUnknownFields(bool $value = true): void
{
static::$globalFailOnUnknownFields = $value;
}
/**
* Set the Validator instance.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return $this
*/
public function setValidator(Validator $validator)
{
$this->validator = $validator;
return $this;
}
/**
* Set the Redirector instance.
*
* @param \Illuminate\Routing\Redirector $redirector
* @return $this
*/
public function setRedirector(Redirector $redirector)
{
$this->redirector = $redirector;
return $this;
}
/**
* Set the container implementation.
*
* @param \Illuminate\Contracts\Container\Container $container
* @return $this
*/
public function setContainer(Container $container)
{
$this->container = $container;
return $this;
}
}