Skip to content

Commit 7c7b1dd

Browse files
committed
refactor(http): reshape typed request input API
Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent d7dc8d2 commit 7c7b1dd

7 files changed

Lines changed: 232 additions & 138 deletions

File tree

‎system/HTTP/IncomingRequest.php‎

Lines changed: 8 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
use CodeIgniter\HTTP\Exceptions\HTTPException;
1818
use CodeIgniter\HTTP\Files\FileCollection;
1919
use CodeIgniter\HTTP\Files\UploadedFile;
20-
use CodeIgniter\Input\InputData;
2120
use Config\App;
2221
use Config\Services;
2322
use Locale;
@@ -556,40 +555,6 @@ public function getRawInputVar($index = null, ?int $filter = null, $flags = null
556555
return $output;
557556
}
558557

559-
/**
560-
* Returns GET parameters as a typed input object.
561-
*/
562-
public function getGetInput(): InputData
563-
{
564-
$data = $this->getGet();
565-
566-
return service('inputdatafactory')->create(is_array($data) ? $data : []);
567-
}
568-
569-
/**
570-
* Returns POST body parameters as a typed input object.
571-
*/
572-
public function getPostInput(): InputData
573-
{
574-
$data = $this->getPost();
575-
576-
return service('inputdatafactory')->create(is_array($data) ? $data : []);
577-
}
578-
579-
/**
580-
* Returns JSON body parameters as a typed input object.
581-
*/
582-
public function getJSONInput(): InputData
583-
{
584-
$data = $this->getJSON(true) ?? [];
585-
586-
if (! is_array($data)) {
587-
throw HTTPException::forUnsupportedJSONFormat();
588-
}
589-
590-
return service('inputdatafactory')->create($data);
591-
}
592-
593558
/**
594559
* Fetch an item from GET data.
595560
*
@@ -604,6 +569,14 @@ public function getGet($index = null, $filter = null, $flags = null)
604569
return $this->fetchGlobal('get', $index, $filter, $flags);
605570
}
606571

572+
/**
573+
* Returns a typed input data selector.
574+
*/
575+
public function input(): RequestInput
576+
{
577+
return new RequestInput($this, service('inputdatafactory'));
578+
}
579+
607580
/**
608581
* Fetch an item from POST.
609582
*

‎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+
}

‎tests/system/HTTP/IncomingRequestTest.php‎

Lines changed: 0 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
use CodeIgniter\Exceptions\InvalidArgumentException;
2020
use CodeIgniter\HTTP\Exceptions\HTTPException;
2121
use CodeIgniter\HTTP\Files\UploadedFile;
22-
use CodeIgniter\Input\InputData;
2322
use CodeIgniter\Superglobals;
2423
use CodeIgniter\Test\CIUnitTestCase;
2524
use Config\App;
@@ -87,35 +86,6 @@ public function testCanGrabPostVars(): void
8786
$this->assertNull($this->request->getPost('TESTY'));
8887
}
8988

90-
public function testGetGetInputReadsGetData(): void
91-
{
92-
service('superglobals')->setGet('page', '3');
93-
service('superglobals')->setGet('filters', ['active' => 'true']);
94-
service('superglobals')->setPost('page', '10');
95-
96-
$request = $this->createRequest();
97-
$input = $request->getGetInput();
98-
99-
$this->assertInstanceOf(InputData::class, $input);
100-
$this->assertSame(3, $input->integer('page'));
101-
$this->assertTrue($input->boolean('filters.active'));
102-
$this->assertSame(1, $input->integer('missing', 1));
103-
}
104-
105-
public function testGetPostInputReadsPostData(): void
106-
{
107-
service('superglobals')->setGet('remember', '0');
108-
service('superglobals')->setPost('remember', '1');
109-
service('superglobals')->setPost('tags', ['php', 'ci4']);
110-
111-
$request = $this->createRequest();
112-
$input = $request->getPostInput();
113-
114-
$this->assertInstanceOf(InputData::class, $input);
115-
$this->assertTrue($input->boolean('remember'));
116-
$this->assertSame(['php', 'ci4'], $input->array('tags'));
117-
}
118-
11989
public function testCanGrabPostBeforeGet(): void
12090
{
12191
service('superglobals')->setPost('TEST', '5');
@@ -602,54 +572,6 @@ public function testCanGrabGetRawInput(): void
602572
$this->assertSame($expected, $request->getRawInput());
603573
}
604574

605-
public function testGetJSONInputReadsJsonBody(): void
606-
{
607-
$json = json_encode([
608-
'page' => '4',
609-
'filters' => ['active' => 'true'],
610-
'nullable' => null,
611-
]);
612-
613-
$request = $this->createRequest(new App(), $json);
614-
615-
$input = $request->getJSONInput();
616-
617-
$this->assertInstanceOf(InputData::class, $input);
618-
$this->assertSame(4, $input->integer('page'));
619-
$this->assertTrue($input->boolean('filters.active'));
620-
$this->assertTrue($input->has('nullable'));
621-
}
622-
623-
public function testGetJSONInputReturnsEmptyInputForEmptyJsonBody(): void
624-
{
625-
$request = $this->createRequest(new App());
626-
627-
$input = $request->getJSONInput();
628-
629-
$this->assertInstanceOf(InputData::class, $input);
630-
$this->assertFalse($input->has('name'));
631-
}
632-
633-
public function testGetJSONInputRejectsScalarJsonBody(): void
634-
{
635-
$this->expectException(HTTPException::class);
636-
$this->expectExceptionMessage('The provided JSON format is not supported.');
637-
638-
$request = $this->createRequest(new App(), '"hello"');
639-
640-
$request->getJSONInput();
641-
}
642-
643-
public function testGetJSONInputKeepsInvalidJsonError(): void
644-
{
645-
$this->expectException(HTTPException::class);
646-
$this->expectExceptionMessage('Failed to parse JSON string. Error: Syntax error');
647-
648-
$request = $this->createRequest(new App(), 'Invalid JSON string');
649-
650-
$request->getJSONInput();
651-
}
652-
653575
/**
654576
* @param string $rawstring
655577
* @param mixed $var
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
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 testGetReadsGetData(): void
60+
{
61+
service('superglobals')->setGet('page', '3');
62+
service('superglobals')->setGet('filters', ['active' => 'true']);
63+
service('superglobals')->setPost('page', '10');
64+
65+
$input = $this->createRequest()->input()->get();
66+
67+
$this->assertInstanceOf(InputData::class, $input);
68+
$this->assertSame(3, $input->integer('page'));
69+
$this->assertTrue($input->boolean('filters.active'));
70+
$this->assertSame(1, $input->integer('missing', 1));
71+
}
72+
73+
public function testPostReadsPostData(): void
74+
{
75+
service('superglobals')->setGet('remember', '0');
76+
service('superglobals')->setPost('remember', '1');
77+
service('superglobals')->setPost('tags', ['php', 'ci4']);
78+
79+
$input = $this->createRequest()->input()->post();
80+
81+
$this->assertInstanceOf(InputData::class, $input);
82+
$this->assertTrue($input->boolean('remember'));
83+
$this->assertSame(['php', 'ci4'], $input->array('tags'));
84+
}
85+
86+
public function testJsonReadsJsonBody(): void
87+
{
88+
$json = json_encode([
89+
'page' => '4',
90+
'filters' => ['active' => 'true'],
91+
'nullable' => null,
92+
]);
93+
94+
$input = $this->createRequest(new App(), $json)->input()->json();
95+
96+
$this->assertInstanceOf(InputData::class, $input);
97+
$this->assertSame(4, $input->integer('page'));
98+
$this->assertTrue($input->boolean('filters.active'));
99+
$this->assertTrue($input->has('nullable'));
100+
}
101+
102+
public function testJsonReturnsEmptyInputForEmptyJsonBody(): void
103+
{
104+
$input = $this->createRequest(new App())->input()->json();
105+
106+
$this->assertInstanceOf(InputData::class, $input);
107+
$this->assertFalse($input->has('name'));
108+
}
109+
110+
public function testJsonRejectsScalarJsonBody(): void
111+
{
112+
$this->expectException(HTTPException::class);
113+
$this->expectExceptionMessage('The provided JSON format is not supported.');
114+
115+
$this->createRequest(new App(), '"hello"')->input()->json();
116+
}
117+
118+
public function testJsonKeepsInvalidJsonError(): void
119+
{
120+
$this->expectException(HTTPException::class);
121+
$this->expectExceptionMessage('Failed to parse JSON string. Error: Syntax error');
122+
123+
$this->createRequest(new App(), 'Invalid JSON string')->input()->json();
124+
}
125+
126+
public function testRawReadsRawInputData(): void
127+
{
128+
$input = $this->createRequest(new App(), 'title=Hello&published=1')->input()->raw();
129+
130+
$this->assertInstanceOf(InputData::class, $input);
131+
$this->assertSame('Hello', $input->string('title'));
132+
$this->assertTrue($input->boolean('published'));
133+
}
134+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ HTTP
261261

262262
- 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`.
263263
- 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.
264-
- Added ``IncomingRequest::getGetInput()``, ``getPostInput()``, and ``getJSONInput()`` to read GET, POST, and JSON request data through ``InputData``.
264+
- Added ``IncomingRequest::input()`` to read GET, POST, JSON, and raw request data through ``InputData``.
265265
- Added ``SSEResponse`` class for streaming Server-Sent Events (SSE) over HTTP. See :ref:`server-sent-events`.
266266
- ``Response`` and its child classes no longer require ``Config\App`` passed to their constructors.
267267
Consequently, ``CURLRequest``'s ``$config`` parameter is unused and will be removed in a future release.

0 commit comments

Comments
 (0)