Skip to content

Commit 5ecd922

Browse files
committed
refactor: form request
1 parent 8bff1ef commit 5ecd922

12 files changed

Lines changed: 56 additions & 146 deletions

File tree

system/HTTP/FormRequest.php

Lines changed: 2 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -178,49 +178,19 @@ protected function failedAuthorization(): ResponseInterface
178178
*
179179
* @return array<string, mixed>
180180
*/
181-
public function validated(): array
181+
public function getValidated(): array
182182
{
183183
return $this->validatedData;
184184
}
185185

186186
/**
187187
* Returns the validated data as a typed input object.
188188
*/
189-
public function validatedInput(): ValidatedInput
189+
public function getValidatedInput(): ValidatedInput
190190
{
191191
return service('inputdatafactory')->createValidated($this->validatedData);
192192
}
193193

194-
/**
195-
* Returns a single validated field value by name, or the default value
196-
* if the field is not present in the validated data.
197-
*
198-
* Supports dot-array syntax for nested validated data.
199-
*/
200-
public function getValidated(string $key, mixed $default = null): mixed
201-
{
202-
helper('array');
203-
204-
if (! dot_array_has($key, $this->validatedData)) {
205-
return $default;
206-
}
207-
208-
return dot_array_search($key, $this->validatedData);
209-
}
210-
211-
/**
212-
* Returns true when the named field exists in the validated data, even if
213-
* its value is null.
214-
*
215-
* Supports dot-array syntax for nested validated data.
216-
*/
217-
public function hasValidated(string $key): bool
218-
{
219-
helper('array');
220-
221-
return dot_array_has($key, $this->validatedData);
222-
}
223-
224194
/**
225195
* Returns the data to be validated.
226196
*

tests/_support/Controllers/FormRequestController.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,23 @@ class FormRequestController extends Controller
2828
*/
2929
public function index(string $id, ValidPostFormRequest $request, string $format = 'json'): string
3030
{
31-
return json_encode(['id' => $id, 'format' => $format, 'data' => $request->validated()]);
31+
return json_encode(['id' => $id, 'format' => $format, 'data' => $request->getValidated()]);
3232
}
3333

3434
/**
3535
* Receives only a FormRequest (no route params).
3636
*/
3737
public function store(ValidPostFormRequest $request): string
3838
{
39-
return json_encode($request->validated());
39+
return json_encode($request->getValidated());
4040
}
4141

4242
/**
4343
* Receives a route param alongside a FormRequest.
4444
*/
4545
public function update(string $id, ValidPostFormRequest $request): string
4646
{
47-
return json_encode(['id' => $id, 'data' => $request->validated()]);
47+
return json_encode(['id' => $id, 'data' => $request->getValidated()]);
4848
}
4949

5050
/**
@@ -61,7 +61,7 @@ public function show(string $id): string
6161
*/
6262
public function search(ValidPostFormRequest $request, string ...$tags): string
6363
{
64-
return json_encode(['tags' => $tags, 'data' => $request->validated()]);
64+
return json_encode(['tags' => $tags, 'data' => $request->getValidated()]);
6565
}
6666

6767
/**

tests/system/HTTP/FormRequestTest.php

Lines changed: 25 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,11 @@ public function rules(): array
146146
};
147147
}
148148

149-
public function testValidatedReturnsEmptyArrayBeforeResolution(): void
149+
public function testGetValidatedReturnsEmptyArrayBeforeResolution(): void
150150
{
151151
$formRequest = $this->makeFormRequest($this->makeRequest());
152152

153-
$this->assertSame([], $formRequest->validated());
153+
$this->assertSame([], $formRequest->getValidated());
154154
}
155155

156156
// -------------------------------------------------------------------------
@@ -167,11 +167,11 @@ public function testResolveRequestPassesWithValidData(): void
167167

168168
$this->assertSame(
169169
['title' => 'Hello World', 'body' => 'Some body text'],
170-
$formRequest->validated(),
170+
$formRequest->getValidated(),
171171
);
172172
}
173173

174-
public function testValidatedReturnsOnlyFieldsCoveredByRules(): void
174+
public function testGetValidatedReturnsOnlyFieldsCoveredByRules(): void
175175
{
176176
service('superglobals')->setPost('title', 'Hello World');
177177
service('superglobals')->setPost('body', 'Some body text');
@@ -180,81 +180,14 @@ public function testValidatedReturnsOnlyFieldsCoveredByRules(): void
180180
$formRequest = $this->makeFormRequest($this->makeRequest());
181181
$formRequest->resolveRequest();
182182

183-
$validated = $formRequest->validated();
183+
$validated = $formRequest->getValidated();
184184

185185
$this->assertArrayHasKey('title', $validated);
186186
$this->assertArrayHasKey('body', $validated);
187187
$this->assertArrayNotHasKey('extra_field', $validated);
188188
}
189189

190-
// -------------------------------------------------------------------------
191-
// Explicit access to validated fields
192-
// -------------------------------------------------------------------------
193-
194-
public function testGetValidatedReturnsValidatedFieldValue(): void
195-
{
196-
service('superglobals')->setPost('title', 'Hello World');
197-
service('superglobals')->setPost('body', 'Some body text');
198-
199-
$formRequest = new ValidPostFormRequest($this->makeRequest());
200-
$formRequest->resolveRequest();
201-
202-
$this->assertSame('Hello World', $formRequest->getValidated('title'));
203-
$this->assertSame('Some body text', $formRequest->getValidated('body'));
204-
}
205-
206-
public function testGetValidatedReturnsNullForMissingField(): void
207-
{
208-
service('superglobals')->setPost('title', 'Hello World');
209-
service('superglobals')->setPost('body', 'Some body text');
210-
211-
$formRequest = new ValidPostFormRequest($this->makeRequest());
212-
$formRequest->resolveRequest();
213-
214-
$this->assertNull($formRequest->getValidated('nonexistent'));
215-
}
216-
217-
public function testGetValidatedReturnsDefaultForMissingField(): void
218-
{
219-
service('superglobals')->setPost('title', 'Hello World');
220-
service('superglobals')->setPost('body', 'Some body text');
221-
222-
$formRequest = new ValidPostFormRequest($this->makeRequest());
223-
$formRequest->resolveRequest();
224-
225-
$this->assertSame('fallback', $formRequest->getValidated('nonexistent', 'fallback'));
226-
}
227-
228-
public function testGetValidatedReturnsNullBeforeValidationRuns(): void
229-
{
230-
$formRequest = new ValidPostFormRequest($this->makeRequest());
231-
232-
$this->assertNull($formRequest->getValidated('title'));
233-
}
234-
235-
public function testHasValidatedReturnsTrueForValidatedField(): void
236-
{
237-
service('superglobals')->setPost('title', 'Hello World');
238-
service('superglobals')->setPost('body', 'Some body text');
239-
240-
$formRequest = new ValidPostFormRequest($this->makeRequest());
241-
$formRequest->resolveRequest();
242-
243-
$this->assertTrue($formRequest->hasValidated('title'));
244-
}
245-
246-
public function testHasValidatedReturnsFalseForMissingField(): void
247-
{
248-
service('superglobals')->setPost('title', 'Hello World');
249-
service('superglobals')->setPost('body', 'Some body text');
250-
251-
$formRequest = new ValidPostFormRequest($this->makeRequest());
252-
$formRequest->resolveRequest();
253-
254-
$this->assertFalse($formRequest->hasValidated('nonexistent'));
255-
}
256-
257-
public function testGetValidatedAndHasValidatedSupportDotSyntax(): void
190+
public function testGetValidatedReturnsNestedValidatedData(): void
258191
{
259192
service('superglobals')->setPost('post', [
260193
'title' => 'Hello World',
@@ -275,12 +208,20 @@ public function rules(): array
275208

276209
$formRequest->resolveRequest();
277210

278-
$this->assertSame('Hello World', $formRequest->getValidated('post.title'));
279-
$this->assertSame('hello-world', $formRequest->getValidated('post.meta.slug'));
280-
$this->assertTrue($formRequest->hasValidated('post.meta.slug'));
211+
$this->assertSame(
212+
[
213+
'post' => [
214+
'title' => 'Hello World',
215+
'meta' => [
216+
'slug' => 'hello-world',
217+
],
218+
],
219+
],
220+
$formRequest->getValidated(),
221+
);
281222
}
282223

283-
public function testHasValidatedReturnsTrueForNullValidatedField(): void
224+
public function testGetValidatedReturnsNullValidatedField(): void
284225
{
285226
service('superglobals')->setServer('CONTENT_TYPE', 'application/json');
286227

@@ -293,21 +234,18 @@ public function rules(): array
293234

294235
$formRequest->resolveRequest();
295236

296-
$this->assertSame(['note' => null], $formRequest->validated());
297-
$this->assertNull($formRequest->getValidated('note'));
298-
$this->assertNull($formRequest->getValidated('note', 'fallback'));
299-
$this->assertTrue($formRequest->hasValidated('note'));
237+
$this->assertSame(['note' => null], $formRequest->getValidated());
300238
}
301239

302-
public function testValidatedInputReturnsValidatedInputObject(): void
240+
public function testGetValidatedInputReturnsValidatedInputObject(): void
303241
{
304242
service('superglobals')->setPost('title', 'Hello World');
305243
service('superglobals')->setPost('body', 'Some body text');
306244

307245
$formRequest = new ValidPostFormRequest($this->makeRequest());
308246
$formRequest->resolveRequest();
309247

310-
$input = $formRequest->validatedInput();
248+
$input = $formRequest->getValidatedInput();
311249

312250
$this->assertInstanceOf(ValidatedInput::class, $input);
313251
$this->assertSame('Hello World', $input->get('title'));
@@ -343,7 +281,7 @@ protected function prepareForValidation(array $data): array
343281
$this->assertNotInstanceOf(ResponseInterface::class, $formRequest->resolveRequest());
344282

345283
$this->assertTrue($formRequest::$prepareCalled);
346-
$this->assertSame('Hi extended', $formRequest->validated()['title']);
284+
$this->assertSame('Hi extended', $formRequest->getValidated()['title']);
347285
}
348286

349287
// -------------------------------------------------------------------------
@@ -499,7 +437,7 @@ protected function validationData(): array
499437

500438
$this->assertNotInstanceOf(ResponseInterface::class, $formRequest->resolveRequest());
501439

502-
$this->assertSame('Injected Title', $formRequest->validated()['title']);
440+
$this->assertSame('Injected Title', $formRequest->getValidated()['title']);
503441
}
504442

505443
public function testCustomFailedValidationIsRespected(): void
@@ -708,7 +646,7 @@ public function testClosureRouteWithFormRequestIsInjected(): void
708646

709647
$routes = service('routes');
710648
$routes->setAutoRoute(false);
711-
$routes->add('closure/(:segment)', static fn (string $id, ValidPostFormRequest $request): string => json_encode(['id' => $id, 'data' => $request->validated()]));
649+
$routes->add('closure/(:segment)', static fn (string $id, ValidPostFormRequest $request): string => json_encode(['id' => $id, 'data' => $request->getValidated()]));
712650

713651
$router = service('router', $routes, service('incomingrequest'));
714652
Services::injectMock('router', $router);
@@ -781,7 +719,7 @@ public function testUnauthorizedFormRequestReturns403(): void
781719
}
782720

783721
// -------------------------------------------------------------------------
784-
// Integration: validated() only returns fields declared in rules()
722+
// Integration: getValidated() only returns fields declared in rules()
785723
// -------------------------------------------------------------------------
786724

787725
#[RunInSeparateProcess]

user_guide_src/source/incoming/form_requests.rst

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -49,26 +49,26 @@ JSON/AJAX requests - the method body is never reached.
4949
Accessing Validated Data
5050
************************
5151

52-
``validated()`` returns an array containing only the fields that were declared
52+
``getValidated()`` returns an array containing only the fields that were declared
5353
in ``rules()``. Fields submitted by the client that are not covered by a rule
5454
are silently discarded, protecting against mass-assignment.
5555

5656
.. literalinclude:: form_requests/009.php
5757
:lines: 2-
5858

59-
Use ``getValidated()`` to read a single validated field and ``hasValidated()``
60-
to check whether a validated key exists, including keys whose value is
61-
``null``. Both methods support dot-array syntax for nested validated data:
59+
Use ``getValidatedInput()`` when you want to read a single validated field or
60+
check whether a validated key exists, including keys whose value is ``null``.
61+
The input object supports dot-array syntax for nested validated data:
6262

6363
.. literalinclude:: form_requests/014.php
6464
:lines: 2-
6565

6666
Typed Validated Input
6767
=====================
6868

69-
``validatedInput()`` returns the same validated data as a typed input object.
70-
This keeps the array-based APIs unchanged while making common controller values
71-
easier to read after validation has succeeded.
69+
``getValidatedInput()`` returns the same validated data as a typed input object.
70+
This complements ``getValidated()`` by making common controller values easier
71+
to read after validation has succeeded.
7272

7373
After the FormRequest has been validated, read the successful values in the
7474
controller:
@@ -83,7 +83,7 @@ for the full behavior of the typed input methods.
8383
Accessing Other Request Data
8484
============================
8585

86-
For anything not covered by ``validated()`` - uploaded files, request headers,
86+
For anything not covered by ``getValidated()`` - uploaded files, request headers,
8787
the client IP address, raw input, and so on - use ``$this->request`` as usual.
8888
It is the same :doc:`IncomingRequest </incoming/incomingrequest>` instance that
8989
the FormRequest uses internally:
@@ -171,7 +171,7 @@ normalized phone numbers, or trimmed strings.
171171
:lines: 2-
172172

173173
.. note:: ``old()`` returns the original submitted input, not the normalized
174-
values. Use ``validated()`` to access the processed data after a successful
174+
values. Use ``getValidated()`` to access the processed data after a successful
175175
request. If you need ``old()`` to reflect normalized values, see
176176
:ref:`form-request-flash-normalized`.
177177

@@ -245,8 +245,8 @@ whose type extends ``FormRequest``:
245245
rules are applied.
246246
#. ``run()`` executes the validation rules. If it fails, ``failedValidation()``
247247
is called, and its response is returned to the client.
248-
#. The validated data is stored internally and available via ``validated()``,
249-
``validatedInput()``, ``getValidated()``, and ``hasValidated()``.
248+
#. The validated data is stored internally and available via ``getValidated()``
249+
and ``getValidatedInput()``.
250250
#. The resolved FormRequest object is injected into the controller method or
251251
closure.
252252

user_guide_src/source/incoming/form_requests/002.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ class Posts extends BaseController
88
{
99
public function store(StorePostRequest $request): string
1010
{
11-
// $request->validated() returns only the fields declared in rules().
12-
$data = $request->validated();
11+
// $request->getValidated() returns only the fields declared in rules().
12+
$data = $request->getValidated();
1313

1414
// save to database
1515

user_guide_src/source/incoming/form_requests/003.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ class Posts extends BaseController
99
// Route parameters come first; FormRequest follows.
1010
public function update(int $id, UpdatePostRequest $request): string
1111
{
12-
$data = $request->validated();
12+
$data = $request->getValidated();
1313

1414
// update post $id with $data
1515

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
<?php
22

3-
$data = $request->validated();
3+
$data = $request->getValidated();
44
// ['title' => 'My post title', 'body' => 'Body text']

user_guide_src/source/incoming/form_requests/010.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ class Posts extends BaseController
88
{
99
public function store(StorePostRequest $request): string
1010
{
11-
$data = $request->validated();
11+
$data = $request->getValidated();
1212
$files = $this->request->getFiles();
1313

1414
// ...

0 commit comments

Comments
 (0)