Skip to content

Commit ed854ac

Browse files
authored
feat: add source-specific typed request input (#10216)
1 parent 800a72b commit ed854ac

7 files changed

Lines changed: 281 additions & 2 deletions

File tree

‎structarmed.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@
100100
'Files' => ['I18n'],
101101
'Filters' => ['HTTP'],
102102
'Honeypot' => ['Filters', 'HTTP'],
103-
'HTTP' => ['Cookie', 'Files', 'I18n', 'Security', 'URI'],
103+
'HTTP' => ['Cookie', 'Files', 'I18n', 'Input', 'Security', 'URI'],
104104
'Images' => ['Files', 'I18n'],
105105
'Lock' => ['Cache'],
106106
'Model' => ['Database', 'DataCaster', 'DataConverter', 'Entity', 'I18n', 'Pager', 'Validation'],

‎system/HTTP/IncomingRequest.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ class IncomingRequest extends Request
123123
*/
124124
protected $userAgent;
125125

126+
/**
127+
* Typed input data selector.
128+
*/
129+
protected ?RequestInput $input = null;
130+
126131
/**
127132
* Constructor
128133
*
@@ -169,6 +174,11 @@ public function __construct($config, ?URI $uri = null, $body = 'php://input', ?U
169174
$this->detectLocale($config);
170175
}
171176

177+
public function __clone()
178+
{
179+
$this->input = null;
180+
}
181+
172182
private function getPostMaxSize(): int
173183
{
174184
$postMaxSize = ini_get('post_max_size');
@@ -569,6 +579,14 @@ public function getGet($index = null, $filter = null, $flags = null)
569579
return $this->fetchGlobal('get', $index, $filter, $flags);
570580
}
571581

582+
/**
583+
* Returns a typed input data selector.
584+
*/
585+
public function input(): RequestInput
586+
{
587+
return $this->input ??= new RequestInput($this, service('inputdatafactory'));
588+
}
589+
572590
/**
573591
* Fetch an item from POST.
574592
*

‎system/HTTP/RequestInput.php‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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 CodeIgniter\HTTP;
15+
16+
use CodeIgniter\HTTP\Exceptions\HTTPException;
17+
use CodeIgniter\Input\InputData;
18+
use CodeIgniter\Input\InputDataFactory;
19+
20+
/**
21+
* Provides typed input access for request data sources.
22+
*
23+
* @see \CodeIgniter\HTTP\RequestInputTest
24+
*/
25+
final readonly class RequestInput
26+
{
27+
public function __construct(
28+
private IncomingRequest $request,
29+
private InputDataFactory $factory,
30+
) {
31+
}
32+
33+
/**
34+
* Returns GET parameters as a typed input object.
35+
*/
36+
public function get(): InputData
37+
{
38+
$data = $this->request->getGet();
39+
40+
return $this->factory->create(is_array($data) ? $data : []);
41+
}
42+
43+
/**
44+
* Returns POST body parameters as a typed input object.
45+
*/
46+
public function post(): InputData
47+
{
48+
$data = $this->request->getPost();
49+
50+
return $this->factory->create(is_array($data) ? $data : []);
51+
}
52+
53+
/**
54+
* Returns JSON body parameters as a typed input object.
55+
*/
56+
public function json(): InputData
57+
{
58+
$data = $this->request->getJSON(true) ?? [];
59+
60+
if (! is_array($data)) {
61+
throw HTTPException::forUnsupportedJSONFormat();
62+
}
63+
64+
return $this->factory->create($data);
65+
}
66+
67+
/**
68+
* Returns raw input parameters as a typed input object.
69+
*/
70+
public function raw(): InputData
71+
{
72+
return $this->factory->create($this->request->getRawInput());
73+
}
74+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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 CodeIgniter\HTTP;
15+
16+
use CodeIgniter\Config\Services;
17+
use CodeIgniter\HTTP\Exceptions\HTTPException;
18+
use CodeIgniter\Input\InputData;
19+
use CodeIgniter\Superglobals;
20+
use CodeIgniter\Test\CIUnitTestCase;
21+
use Config\App;
22+
use PHPUnit\Framework\Attributes\BackupGlobals;
23+
use PHPUnit\Framework\Attributes\Group;
24+
25+
/**
26+
* @internal
27+
*/
28+
#[BackupGlobals(true)]
29+
#[Group('SeparateProcess')]
30+
final class RequestInputTest extends CIUnitTestCase
31+
{
32+
protected function setUp(): void
33+
{
34+
parent::setUp();
35+
36+
Services::injectMock('superglobals', new Superglobals([], [], [], [], [], []));
37+
}
38+
39+
private function createRequest(?App $config = null, ?string $body = null): IncomingRequest
40+
{
41+
$config ??= new App();
42+
43+
return new IncomingRequest(
44+
$config,
45+
new SiteURI($config, ''),
46+
$body,
47+
new UserAgent(),
48+
);
49+
}
50+
51+
public function testInputReturnsRequestInput(): void
52+
{
53+
$request = $this->createRequest();
54+
$input = $request->input();
55+
56+
$this->assertInstanceOf(RequestInput::class, $input);
57+
}
58+
59+
public function testInputReturnsSameRequestInputInstance(): void
60+
{
61+
$request = $this->createRequest();
62+
63+
$this->assertSame($request->input(), $request->input());
64+
}
65+
66+
public function testClonedRequestGetsNewRequestInputInstance(): void
67+
{
68+
$request = $this->createRequest();
69+
$input = $request->input();
70+
71+
$clonedRequest = $request->withMethod(Method::POST);
72+
73+
$this->assertNotSame($input, $clonedRequest->input());
74+
}
75+
76+
public function testGetReadsGetData(): void
77+
{
78+
service('superglobals')->setGet('page', '3');
79+
service('superglobals')->setGet('filters', ['active' => 'true']);
80+
service('superglobals')->setPost('page', '10');
81+
82+
$input = $this->createRequest()->input()->get();
83+
84+
$this->assertInstanceOf(InputData::class, $input);
85+
$this->assertSame(3, $input->integer('page'));
86+
$this->assertTrue($input->boolean('filters.active'));
87+
$this->assertSame(1, $input->integer('missing', 1));
88+
}
89+
90+
public function testPostReadsPostData(): void
91+
{
92+
service('superglobals')->setGet('remember', '0');
93+
service('superglobals')->setPost('remember', '1');
94+
service('superglobals')->setPost('tags', ['php', 'ci4']);
95+
96+
$input = $this->createRequest()->input()->post();
97+
98+
$this->assertInstanceOf(InputData::class, $input);
99+
$this->assertTrue($input->boolean('remember'));
100+
$this->assertSame(['php', 'ci4'], $input->array('tags'));
101+
}
102+
103+
public function testJsonReadsJsonBody(): void
104+
{
105+
$json = json_encode([
106+
'page' => '4',
107+
'filters' => ['active' => 'true'],
108+
'nullable' => null,
109+
]);
110+
111+
$input = $this->createRequest(new App(), $json)->input()->json();
112+
113+
$this->assertInstanceOf(InputData::class, $input);
114+
$this->assertSame(4, $input->integer('page'));
115+
$this->assertTrue($input->boolean('filters.active'));
116+
$this->assertTrue($input->has('nullable'));
117+
}
118+
119+
public function testJsonReturnsEmptyInputForEmptyJsonBody(): void
120+
{
121+
$input = $this->createRequest(new App())->input()->json();
122+
123+
$this->assertInstanceOf(InputData::class, $input);
124+
$this->assertFalse($input->has('name'));
125+
}
126+
127+
public function testJsonRejectsScalarJsonBody(): void
128+
{
129+
$this->expectException(HTTPException::class);
130+
$this->expectExceptionMessage('The provided JSON format is not supported.');
131+
132+
$this->createRequest(new App(), '"hello"')->input()->json();
133+
}
134+
135+
public function testJsonKeepsInvalidJsonError(): void
136+
{
137+
$this->expectException(HTTPException::class);
138+
$this->expectExceptionMessage('Failed to parse JSON string. Error: Syntax error');
139+
140+
$this->createRequest(new App(), 'Invalid JSON string')->input()->json();
141+
}
142+
143+
public function testRawReadsRawInputData(): void
144+
{
145+
$input = $this->createRequest(new App(), 'title=Hello&published=1')->input()->raw();
146+
147+
$this->assertInstanceOf(InputData::class, $input);
148+
$this->assertSame('Hello', $input->string('title'));
149+
$this->assertTrue($input->boolean('published'));
150+
}
151+
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,7 @@ HTTP
271271

272272
- Added the ``retry`` option to ``CURLRequest`` for retrying failed responses with configurable delays, retryable status codes, optional transient cURL error retries, and ``Retry-After`` support. See :ref:`curlrequest-request-options-retry`.
273273
- Added :ref:`Form Requests <form-requests>` - a new ``FormRequest`` base class that encapsulates validation rules, custom error messages, and authorization logic for a single HTTP request.
274+
- Added ``IncomingRequest::input()`` to read GET, POST, JSON, and raw request data through ``InputData``.
274275
- Added ``SSEResponse`` class for streaming Server-Sent Events (SSE) over HTTP. See :ref:`server-sent-events`.
275276
- ``Response`` and its child classes no longer require ``Config\App`` passed to their constructors.
276277
Consequently, ``CURLRequest``'s ``$config`` parameter is unused and will be removed in a future release.

‎user_guide_src/source/incoming/incomingrequest.rst‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,30 @@ The ``getVar()`` method will pull from ``$_REQUEST``, so will return any data fr
161161
.. note:: If the incoming request has a ``Content-Type`` header set to ``application/json``,
162162
the ``getVar()`` method returns the JSON data instead of ``$_REQUEST`` data.
163163

164+
.. _incomingrequest-typed-request-input:
165+
166+
Typed Request Input
167+
===================
168+
169+
.. versionadded:: 4.8.0
170+
171+
``input()`` returns a ``CodeIgniter\HTTP\RequestInput`` object. Use it to read
172+
values from a specific part of the request with typed fallback helpers:
173+
174+
.. literalinclude:: incomingrequest/046.php
175+
:lines: 2-
176+
177+
``input()->get()`` reads query-string parameters. ``input()->post()`` reads
178+
POST body parameters. ``input()->json()`` reads JSON request body parameters.
179+
``input()->raw()`` reads raw input parameters, like ``getRawInput()``.
180+
181+
These methods keep GET, POST, JSON, and raw data separate. They do not combine
182+
multiple request sources for you.
183+
184+
These methods do not validate input. They are fallback-friendly helpers for
185+
reading raw request data. Use Validation or :ref:`form-requests` when input
186+
must satisfy application rules before it is consumed.
187+
164188
.. _incomingrequest-getting-json-data:
165189

166190
Getting JSON Data
@@ -227,6 +251,7 @@ Filtering a POST variable would look like this:
227251

228252
All of the methods mentioned above support the filter type passed in as the second parameter, with the
229253
exception of ``getJSON()`` and ``getRawInput()``.
254+
The typed input helpers returned by ``input()`` do not accept filter parameters.
230255

231256
Retrieving Headers
232257
******************
@@ -406,6 +431,11 @@ The methods provided by the parent classes that are available are:
406431

407432
.. literalinclude:: incomingrequest/045.php
408433

434+
.. php:method:: input()
435+
436+
:returns: A typed input data selector.
437+
:rtype: CodeIgniter\\HTTP\\RequestInput
438+
409439
.. php:method:: getPost([$index = null[, $filter = null[, $flags = null]]])
410440
411441
:param string $index: The name of the variable/key to look for.
@@ -519,4 +549,3 @@ The methods provided by the parent classes that are available are:
519549
.. note:: Prior to v4.4.0, this was the safest method to determine the
520550
"current URI", since ``IncomingRequest::$uri`` might not be aware of
521551
the complete App configuration for base URLs.
522-
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php
2+
3+
$page = $request->input()->get()->integer('page', 1);
4+
$remember = $request->input()->post()->boolean('remember', false);
5+
$name = $request->input()->json()->string('name');
6+
$published = $request->input()->raw()->boolean('published', false);

0 commit comments

Comments
 (0)