Skip to content

Commit d8f51d8

Browse files
committed
feat: add IncomingRequest::is() method
1 parent cfd0208 commit d8f51d8

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

system/HTTP/IncomingRequest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,30 @@ public function negotiate(string $type, array $supported, bool $strictMatch = fa
375375
throw HTTPException::forInvalidNegotiationType($type);
376376
}
377377

378+
/**
379+
* Checks if this request is.
380+
*
381+
* @param string $value HTTP verb or 'json'
382+
* @phpstan-param 'get'|'post'|'put'|'delete'|'head'|'patch'|'options'|'json' $value
383+
*/
384+
public function is(string $value): bool
385+
{
386+
$value = strtolower($value);
387+
388+
$httpMethods = ['get', 'post', 'put', 'delete', 'head', 'patch', 'options'];
389+
390+
if (in_array($value, $httpMethods, true)) {
391+
return strtolower($this->getMethod()) === $value;
392+
}
393+
394+
if ($value === 'json') {
395+
return strpos($this->getHeaderLine('Content-Type'), 'application/json') !== false;
396+
}
397+
398+
// @phpstan-ignore-next-line
399+
throw new InvalidArgumentException('Unknown value: ' . $value);
400+
}
401+
378402
/**
379403
* Determines if this request was made from the command line (CLI).
380404
*/

tests/system/HTTP/IncomingRequestTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use CodeIgniter\HTTP\Files\UploadedFile;
1717
use CodeIgniter\Test\CIUnitTestCase;
1818
use Config\App;
19+
use Generator;
1920
use TypeError;
2021

2122
/**
@@ -615,6 +616,46 @@ public function testCanGrabGetRawInputVar($rawstring, $var, $expected, $filter,
615616
$this->assertSame($expected, $request->getRawInputVar($var, $filter, $flag));
616617
}
617618

619+
/**
620+
* @dataProvider provideIsHTTPMethods
621+
*/
622+
public function testIsHTTPMethodLowerCase(string $value)
623+
{
624+
$request = $this->request->withMethod($value);
625+
626+
$this->assertTrue($request->is($value));
627+
}
628+
629+
public function provideIsHTTPMethods(): Generator
630+
{
631+
yield from [
632+
['get'],
633+
['post'],
634+
['put'],
635+
['delete'],
636+
['head'],
637+
['patch'],
638+
['options'],
639+
];
640+
}
641+
642+
/**
643+
* @dataProvider provideIsHTTPMethods
644+
*/
645+
public function testIsHTTPMethodUpperCase(string $value)
646+
{
647+
$request = $this->request->withMethod(strtoupper($value));
648+
649+
$this->assertTrue($request->is($value));
650+
}
651+
652+
public function testIsJson()
653+
{
654+
$request = $this->request->setHeader('Content-Type', 'application/json');
655+
656+
$this->assertTrue($request->is('json'));
657+
}
658+
618659
public function testIsCLI()
619660
{
620661
$this->assertFalse($this->request->isCLI());

0 commit comments

Comments
 (0)