diff --git a/flight/net/Request.php b/flight/net/Request.php index 146c641..7fd8592 100644 --- a/flight/net/Request.php +++ b/flight/net/Request.php @@ -315,6 +315,24 @@ class Request return self::getVar($header, $default); } + /** + * Gets all the request headers + * + * @return array + */ + 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. * diff --git a/tests/RequestTest.php b/tests/RequestTest.php index 469c581..8a9f9b5 100644 --- a/tests/RequestTest.php +++ b/tests/RequestTest.php @@ -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()); + } }