Skip to content

Commit c89f983

Browse files
committed
refactor: pass prepared FormRequest data to failedValidation
Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent e92187e commit c89f983

5 files changed

Lines changed: 100 additions & 52 deletions

File tree

‎system/HTTP/FormRequest.php‎

Lines changed: 19 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,6 @@ abstract class FormRequest
3535
*/
3636
private array $validatedData = [];
3737

38-
/**
39-
* Data after prepareForValidation() and before validation rules run.
40-
*
41-
* @var array<string, mixed>
42-
*/
43-
private array $preparedValidationData = [];
44-
4538
/**
4639
* When called by the framework, the current IncomingRequest is injected
4740
* explicitly. When instantiated manually (e.g. in tests), the constructor
@@ -150,21 +143,6 @@ protected function prepareForValidation(array $data): array
150143
return $data;
151144
}
152145

153-
/**
154-
* Returns the data after prepareForValidation() has run.
155-
*
156-
* This is useful in failedValidation() when a custom failure response needs
157-
* the same prepared data that was passed to validation. This data has not
158-
* passed validation; use getValidated() or getValidatedInput() after
159-
* successful validation for trusted values.
160-
*
161-
* @return array<string, mixed>
162-
*/
163-
protected function getPreparedValidationData(): array
164-
{
165-
return $this->preparedValidationData;
166-
}
167-
168146
/**
169147
* Called when validation fails. Override to customize the failure response.
170148
*
@@ -175,14 +153,27 @@ protected function getPreparedValidationData(): array
175153
* returns a 422 JSON response instead.
176154
*
177155
* @param array<string, string> $errors
156+
* @param array<string, mixed> $preparedData
178157
*/
179-
protected function failedValidation(array $errors): ResponseInterface
158+
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
180159
{
181160
if ($this->shouldReturnJsonResponse()) {
182161
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
183162
}
184163

185-
return redirect()->back()->withInput();
164+
$redirect = redirect()->back()->withInput();
165+
166+
$key = in_array($this->request->getMethod(), [Method::GET, Method::HEAD], true)
167+
? 'get'
168+
: 'post';
169+
170+
service('session')->setFlashdata('_ci_old_input', [
171+
'get' => [],
172+
'post' => [],
173+
$key => $preparedData,
174+
]);
175+
176+
return $redirect;
186177
}
187178

188179
/**
@@ -271,20 +262,19 @@ protected function validationData(): array
271262
*/
272263
final public function resolveRequest(): ?ResponseInterface
273264
{
274-
$this->validatedData = [];
275-
$this->preparedValidationData = [];
265+
$this->validatedData = [];
276266

277267
if (! $this->isAuthorized()) {
278268
return $this->failedAuthorization();
279269
}
280270

281-
$this->preparedValidationData = $this->prepareForValidation($this->validationData());
271+
$data = $this->prepareForValidation($this->validationData());
282272

283273
$validation = service('validation')
284274
->setRules($this->rules(), $this->messages());
285275

286-
if (! $validation->run($this->preparedValidationData)) {
287-
return $this->failedValidation($validation->getErrors());
276+
if (! $validation->run($data)) {
277+
return $this->failedValidation($validation->getErrors(), $data);
288278
}
289279

290280
$this->validatedData = $validation->getValidated();

‎tests/system/HTTP/FormRequestTest.php‎

Lines changed: 66 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ public function testResolveRequestRedirectsForWildcardAcceptHeader(): void
395395
$this->assertSame(303, $response->getStatusCode());
396396
}
397397

398-
public function testPreparedValidationDataIsAvailableDuringFailedValidationWithoutPreparingAgain(): void
398+
public function testPreparedValidationDataIsPassedToFailedValidationWithoutPreparingAgain(): void
399399
{
400400
service('superglobals')->setPost('title', ' Hello World ');
401401

@@ -423,9 +423,9 @@ protected function prepareForValidation(array $data): array
423423
return $data;
424424
}
425425

426-
protected function failedValidation(array $errors): ResponseInterface
426+
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
427427
{
428-
$this->preparedData = $this->getPreparedValidationData();
428+
$this->preparedData = $preparedData;
429429

430430
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
431431
}
@@ -437,6 +437,68 @@ protected function failedValidation(array $errors): ResponseInterface
437437
$this->assertSame(['title' => 'Hello World'], $formRequest->preparedData);
438438
}
439439

440+
#[RunInSeparateProcess]
441+
public function testDefaultFailedValidationFlashesPreparedValidationDataAsOldInput(): void
442+
{
443+
/** @var array<string, mixed> $_SESSION */
444+
$_SESSION = [];
445+
446+
service('superglobals')->setPost('title', ' Hello World ');
447+
448+
$formRequest = new class ($this->makeRequest()) extends FormRequest {
449+
public function rules(): array
450+
{
451+
return [
452+
'title' => 'required',
453+
'body' => 'required',
454+
];
455+
}
456+
457+
protected function prepareForValidation(array $data): array
458+
{
459+
$data['title'] = trim($data['title'] ?? '');
460+
461+
return $data;
462+
}
463+
};
464+
465+
$formRequest->resolveRequest();
466+
467+
$this->assertSame(['title' => 'Hello World'], $_SESSION['_ci_old_input']['post']);
468+
}
469+
470+
#[RunInSeparateProcess]
471+
public function testDefaultFailedValidationFlashesPreparedGetDataAsOldInput(): void
472+
{
473+
/** @var array<string, mixed> $_SESSION */
474+
$_SESSION = [];
475+
476+
service('superglobals')->setServer('REQUEST_METHOD', 'GET');
477+
service('superglobals')->setGet('title', ' Hello World ');
478+
479+
$formRequest = new class ($this->makeRequest()) extends FormRequest {
480+
public function rules(): array
481+
{
482+
return [
483+
'title' => 'required',
484+
'body' => 'required',
485+
];
486+
}
487+
488+
protected function prepareForValidation(array $data): array
489+
{
490+
$data['title'] = trim($data['title'] ?? '');
491+
492+
return $data;
493+
}
494+
};
495+
496+
$formRequest->resolveRequest();
497+
498+
$this->assertSame(['title' => 'Hello World'], $_SESSION['_ci_old_input']['get']);
499+
$this->assertSame([], $_SESSION['_ci_old_input']['post']);
500+
}
501+
440502
// -------------------------------------------------------------------------
441503
// Authorization failure
442504
// -------------------------------------------------------------------------
@@ -530,7 +592,7 @@ public function rules(): array
530592
return ['title' => 'required'];
531593
}
532594

533-
protected function failedValidation(array $errors): ResponseInterface
595+
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
534596
{
535597
self::$called = true;
536598

‎user_guide_src/source/incoming/form_requests.rst‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,9 @@ normalized phone numbers, or trimmed strings.
171171
.. literalinclude:: form_requests/006.php
172172
:lines: 2-
173173

174-
.. note:: ``old()`` returns the original submitted input, not the normalized
175-
values. Use ``getValidated()`` to access the processed data after a successful
176-
request. If you need ``old()`` to reflect normalized values, see
177-
:ref:`form-request-flash-normalized`.
174+
.. note:: When validation fails and the default redirect response is used,
175+
``old()`` returns the prepared validation data. Use ``getValidated()`` to
176+
access the processed data after a successful request.
178177

179178
.. _form-request-validation-data:
180179

@@ -225,19 +224,17 @@ Flashing Normalized Input
225224
=========================
226225

227226
If your ``prepareForValidation()`` transforms visible form fields (for example,
228-
trimming strings or canonicalizing values), ``old()`` will return the original
229-
submitted input because the redirect flashes the raw superglobals.
227+
trimming strings or canonicalizing values), the default redirect response flashes
228+
the prepared validation data as old input.
230229

231-
To make ``old()`` reflect the normalized values instead, override
232-
``failedValidation()`` and flash the data returned from
233-
``prepareForValidation()``:
230+
If you override ``failedValidation()`` and still need to flash normalized input,
231+
use the second ``$preparedData`` argument. It contains the same data that was
232+
passed to validation:
234233

235234
.. literalinclude:: form_requests/013.php
236235
:lines: 2-
237236

238-
Use ``getPreparedValidationData()`` inside ``failedValidation()`` to read that
239-
prepared data without running ``prepareForValidation()`` again. The prepared
240-
data has not passed validation. After successful validation, use
237+
The prepared data has not passed validation. After successful validation, use
241238
``getValidated()`` or ``getValidatedInput()`` for trusted values.
242239

243240
*****************************************

‎user_guide_src/source/incoming/form_requests/008.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public function rules(): array
1616
}
1717

1818
// Always respond with JSON, regardless of the request type.
19-
protected function failedValidation(array $errors): ResponseInterface
19+
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
2020
{
2121
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
2222
}

‎user_guide_src/source/incoming/form_requests/013.php‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ protected function prepareForValidation(array $data): array
2222
return $data;
2323
}
2424

25-
// Override so that old() reflects the normalized values on redirect.
26-
protected function failedValidation(array $errors): ResponseInterface
25+
// Override while still flashing the prepared values on redirect.
26+
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
2727
{
2828
if (
2929
$this->request->is('json')
@@ -32,14 +32,13 @@ protected function failedValidation(array $errors): ResponseInterface
3232
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
3333
}
3434

35-
// withInput() flashes the original superglobals and validation errors.
36-
// Then we overwrite old input with the prepared data so old() returns
37-
// the same values that were passed to validation.
35+
// withInput() flashes validation errors. Then we replace old input with
36+
// the same prepared values that were passed to validation.
3837
$redirect = redirect()->back()->withInput();
3938

4039
service('session')->setFlashdata('_ci_old_input', [
4140
'get' => [],
42-
'post' => $this->getPreparedValidationData(),
41+
'post' => $preparedData,
4342
]);
4443

4544
return $redirect;

0 commit comments

Comments
 (0)