Skip to content

Commit 7ee6d0c

Browse files
committed
feat(http): allow FormRequest validation failures to continue
Let `FormRequest::failedValidation()` return `null` when an application wants the controller action to render the invalid response. - Keep existing ResponseInterface short-circuit behavior - Preserve authorization failures as immediate responses - Document controller-handled validation failures Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 874a820 commit 7ee6d0c

7 files changed

Lines changed: 347 additions & 18 deletions

File tree

‎system/CodeIgniter.php‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -801,10 +801,10 @@ private function resolveCallableParams(ReflectionFunctionAbstract $reflection, a
801801
/**
802802
* Instantiates, authorizes, and validates a FormRequest class.
803803
*
804-
* If authorization or validation fails, the FormRequest returns a
805-
* ResponseInterface. The framework wraps it in a FormRequestException
806-
* (which implements ResponsableInterface) so the response is sent
807-
* without reaching the controller method.
804+
* If the FormRequest returns a ResponseInterface, the framework wraps it
805+
* in a FormRequestException (which implements ResponsableInterface) so the
806+
* response is sent without reaching the controller method. When it returns
807+
* null, the FormRequest is injected.
808808
*
809809
* @param class-string<FormRequest> $className
810810
*/

‎system/HTTP/FormRequest.php‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,10 @@ protected function prepareForValidation(array $data): array
144144
}
145145

146146
/**
147-
* Called when validation fails. Override to customize the failure response.
147+
* Called when validation fails.
148+
*
149+
* Override to customize the failure response, or return null to let the
150+
* controller handle the failed validation with the resolved FormRequest.
148151
*
149152
* The default implementation redirects back with input and flashes validation
150153
* errors via the standard ``_ci_validation_errors`` channel (the same channel
@@ -155,7 +158,7 @@ protected function prepareForValidation(array $data): array
155158
* @param array<string, string> $errors
156159
* @param array<string, mixed> $preparedData
157160
*/
158-
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
161+
protected function failedValidation(array $errors, array $preparedData): ?ResponseInterface
159162
{
160163
if ($this->shouldReturnJsonResponse()) {
161164
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
@@ -256,7 +259,8 @@ protected function validationData(): array
256259
* Runs authorization and validation. Called by the framework before
257260
* injecting the FormRequest into the controller method.
258261
*
259-
* Returns null on success, or a ResponseInterface to short-circuit the
262+
* Returns null on success, or when failedValidation() lets the controller
263+
* handle the failure. Returns a ResponseInterface to short-circuit the
260264
* request when authorization or validation fails.
261265
*
262266
* Do not call this method directly unless you are inside a ``_remap()``

‎tests/_support/Controllers/FormRequestController.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
namespace Tests\Support\Controllers;
1515

1616
use CodeIgniter\Controller;
17+
use CodeIgniter\HTTP\ResponseInterface;
18+
use Tests\Support\HTTP\Requests\ContinuingPostFormRequest;
1719
use Tests\Support\HTTP\Requests\UnauthorizedFormRequest;
1820
use Tests\Support\HTTP\Requests\ValidPostFormRequest;
1921

@@ -39,6 +41,22 @@ public function store(ValidPostFormRequest $request): string
3941
return json_encode($request->getValidated());
4042
}
4143

44+
/**
45+
* Handles validation failures in the controller.
46+
*/
47+
public function storeContinuing(ContinuingPostFormRequest $request): ResponseInterface
48+
{
49+
if ($request->errors !== []) {
50+
return $this->response->setStatusCode(422)->setJSON([
51+
'errors' => $request->errors,
52+
'form' => $request->form,
53+
'validated' => $request->getValidated(),
54+
]);
55+
}
56+
57+
return $this->response->setJSON(['validated' => $request->getValidated()]);
58+
}
59+
4260
/**
4361
* Receives a route param alongside a FormRequest.
4462
*/
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Tests\Support\HTTP\Requests;
15+
16+
use CodeIgniter\HTTP\FormRequest;
17+
use CodeIgniter\HTTP\ResponseInterface;
18+
19+
/**
20+
* A FormRequest that lets validation failures reach the controller.
21+
*/
22+
class ContinuingPostFormRequest extends FormRequest
23+
{
24+
/**
25+
* @var array<string, string>
26+
*/
27+
public array $errors = [];
28+
29+
/**
30+
* @var array<string, mixed>
31+
*/
32+
public array $form = [];
33+
34+
public function rules(): array
35+
{
36+
return [
37+
'title' => 'required|min_length[3]',
38+
'body' => 'required',
39+
];
40+
}
41+
42+
protected function prepareForValidation(array $data): array
43+
{
44+
if (isset($data['title'])) {
45+
$data['title'] = trim((string) $data['title']);
46+
}
47+
48+
return $data;
49+
}
50+
51+
protected function failedValidation(array $errors, array $preparedData): ?ResponseInterface
52+
{
53+
$this->errors = $errors;
54+
$this->form = $preparedData;
55+
56+
return null;
57+
}
58+
}

‎tests/system/HTTP/FormRequestTest.php‎

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

398+
public function testFailedValidationMayContinueToController(): void
399+
{
400+
service('superglobals')->setPost('title', ' Hello World ');
401+
402+
$formRequest = new class ($this->makeRequest()) extends FormRequest {
403+
/**
404+
* @var array<string, string>
405+
*/
406+
public array $errors = [];
407+
408+
/**
409+
* @var array<string, mixed>
410+
*/
411+
public array $preparedData = [];
412+
413+
public function rules(): array
414+
{
415+
return [
416+
'title' => 'required',
417+
'body' => 'required',
418+
];
419+
}
420+
421+
protected function prepareForValidation(array $data): array
422+
{
423+
$data['title'] = trim($data['title'] ?? '');
424+
425+
return $data;
426+
}
427+
428+
protected function failedValidation(array $errors, array $preparedData): ?ResponseInterface
429+
{
430+
$this->errors = $errors;
431+
$this->preparedData = $preparedData;
432+
433+
return null;
434+
}
435+
};
436+
437+
$response = $formRequest->resolveRequest();
438+
439+
$this->assertNull($response);
440+
$this->assertArrayHasKey('body', $formRequest->errors);
441+
$this->assertSame(['title' => 'Hello World'], $formRequest->preparedData);
442+
$this->assertSame([], $formRequest->getValidated());
443+
}
444+
445+
public function testNullableFailedValidationFormRequestPassesWithValidData(): void
446+
{
447+
service('superglobals')->setPost('title', ' Hello World ');
448+
service('superglobals')->setPost('body', 'Some body text');
449+
450+
$formRequest = new class ($this->makeRequest()) extends FormRequest {
451+
public bool $failedValidationCalled = false;
452+
453+
public function rules(): array
454+
{
455+
return [
456+
'title' => 'required',
457+
'body' => 'required',
458+
];
459+
}
460+
461+
protected function prepareForValidation(array $data): array
462+
{
463+
$data['title'] = trim($data['title'] ?? '');
464+
465+
return $data;
466+
}
467+
468+
protected function failedValidation(array $errors, array $preparedData): ?ResponseInterface
469+
{
470+
$this->failedValidationCalled = true;
471+
472+
return null;
473+
}
474+
};
475+
476+
$response = $formRequest->resolveRequest();
477+
478+
$this->assertNull($response);
479+
$this->assertFalse($formRequest->failedValidationCalled);
480+
$this->assertSame(['title' => 'Hello World', 'body' => 'Some body text'], $formRequest->getValidated());
481+
}
482+
483+
public function testFailedValidationReturningResponseStillShortCircuits(): void
484+
{
485+
$formRequest = new class ($this->makeRequest()) extends FormRequest {
486+
public static bool $called = false;
487+
488+
public function rules(): array
489+
{
490+
return ['title' => 'required'];
491+
}
492+
493+
protected function failedValidation(array $errors, array $preparedData): ResponseInterface
494+
{
495+
self::$called = true;
496+
497+
return service('response')->setStatusCode(422);
498+
}
499+
};
500+
501+
$response = $formRequest->resolveRequest();
502+
503+
$this->assertInstanceOf(ResponseInterface::class, $response);
504+
$this->assertSame(422, $response->getStatusCode());
505+
$this->assertTrue($formRequest::$called);
506+
}
507+
398508
public function testPreparedValidationDataIsPassedToFailedValidationWithoutPreparingAgain(): void
399509
{
400510
service('superglobals')->setPost('title', ' Hello World ');
@@ -590,6 +700,36 @@ protected function prepareForValidation(array $data): array
590700
$this->assertSame(['authorize'], $formRequest::$order);
591701
}
592702

703+
public function testUnauthorizedRequestStopsBeforeNullableFailedValidation(): void
704+
{
705+
$formRequest = new class ($this->makeRequest()) extends FormRequest {
706+
public bool $failedValidationCalled = false;
707+
708+
public function rules(): array
709+
{
710+
return ['title' => 'required'];
711+
}
712+
713+
public function isAuthorized(): bool
714+
{
715+
return false;
716+
}
717+
718+
protected function failedValidation(array $errors, array $preparedData): ?ResponseInterface
719+
{
720+
$this->failedValidationCalled = true;
721+
722+
return null;
723+
}
724+
};
725+
726+
$response = $formRequest->resolveRequest();
727+
728+
$this->assertInstanceOf(ResponseInterface::class, $response);
729+
$this->assertSame(403, $response->getStatusCode());
730+
$this->assertFalse($formRequest->failedValidationCalled);
731+
}
732+
593733
// -------------------------------------------------------------------------
594734
// Custom overrides
595735
// -------------------------------------------------------------------------
@@ -895,6 +1035,25 @@ public function testInvalidFormRequestRedirectsForAjaxRequest(): void
8951035
$this->assertSame(303, $response->getStatusCode());
8961036
}
8971037

1038+
// -------------------------------------------------------------------------
1039+
// Integration: controller-handled validation failure
1040+
// -------------------------------------------------------------------------
1041+
1042+
#[RunInSeparateProcess]
1043+
public function testContinuingInvalidFormRequestReachesController(): void
1044+
{
1045+
service('superglobals')->setPost('title', ' Draft ');
1046+
1047+
$response = $this->runRequest('/posts/continuing', 'storeContinuing', 'POST');
1048+
1049+
$this->assertSame(422, $response->getStatusCode());
1050+
1051+
$body = json_decode((string) $response->getBody(), true);
1052+
$this->assertArrayHasKey('body', $body['errors']);
1053+
$this->assertSame(['title' => 'Draft'], $body['form']);
1054+
$this->assertSame([], $body['validated']);
1055+
}
1056+
8981057
// -------------------------------------------------------------------------
8991058
// Integration: authorization failure
9001059
// -------------------------------------------------------------------------

0 commit comments

Comments
 (0)