added getHeaders()

pull/533/head
n0nag0n 1 year ago
parent 537ea032d8
commit 2db95a0d7b

@ -315,6 +315,24 @@ class Request
return self::getVar($header, $default);
}
/**
* Gets all the request headers
*
* @return array<string, string|int>
*/
public static function getHeaders(): array
{
$headers = [];
foreach ($_SERVER as $key => $value) {
if (0 === strpos($key, 'HTTP_')) {
// converts headers like HTTP_CUSTOM_HEADER to Custom-Header
$key = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$key] = $value;
}
}
return $headers;
}
/**
* Parse query parameters from a URL.
*

@ -214,4 +214,39 @@ class RequestTest extends \PHPUnit\Framework\TestCase
// default values
$this->assertEquals('default value', $request->getHeader('X-Non-Existent-Header', 'default value'));
}
public function testGetHeaders()
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$request = new Request();
$this->assertEquals(['X-Custom-Header' => 'custom header value'], $request->getHeaders());
}
public function testGetHeadersWithEmptyServer()
{
$_SERVER = [];
$request = new Request();
$this->assertEquals([], $request->getHeaders());
}
public function testGetHeadersWithEmptyHeader()
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = '';
$request = new Request();
$this->assertEquals(['X-Custom-Header' => ''], $request->getHeaders());
}
public function testGetHeadersWithMultipleHeaders()
{
$_SERVER = [];
$_SERVER['HTTP_X_CUSTOM_HEADER'] = 'custom header value';
$_SERVER['HTTP_X_CUSTOM_HEADER2'] = 'custom header value 2';
$request = new Request();
$this->assertEquals([
'X-Custom-Header' => 'custom header value',
'X-Custom-Header2' => 'custom header value 2'
], $request->getHeaders());
}
}

Loading…
Cancel
Save