diff --git a/src/Http/Adapter/Swoole/Request.php b/src/Http/Adapter/Swoole/Request.php index 92b7360..8840cfe 100644 --- a/src/Http/Adapter/Swoole/Request.php +++ b/src/Http/Adapter/Swoole/Request.php @@ -3,6 +3,7 @@ namespace Utopia\Http\Adapter\Swoole; use Swoole\Http\Request as SwooleRequest; +use Stringable; use Utopia\Http\Request as UtopiaRequest; class Request extends UtopiaRequest @@ -287,7 +288,9 @@ public function getCookie(string $key, string $default = ''): string */ public function getHeader(string $key, string $default = ''): string { - return $this->swoole->header[$key] ?? $default; + $key = strtolower($key); + + return $this->normalizeHeaderValue($this->swoole->header[$key] ?? $default, $default); } /** @@ -324,6 +327,27 @@ public function getSwooleRequest(): SwooleRequest return $this->swoole; } + private function normalizeHeaderValue(mixed $value, string $default): string + { + if (is_array($value)) { + for ($i = count($value) - 1; $i >= 0; $i--) { + $candidate = $value[$i]; + + if (is_scalar($candidate) || $candidate instanceof Stringable) { + return (string) $candidate; + } + } + + return $default; + } + + if (is_scalar($value) || $value instanceof Stringable) { + return (string) $value; + } + + return $default; + } + /** * Generate input * diff --git a/tests/SwooleRequestTest.php b/tests/SwooleRequestTest.php new file mode 100644 index 0000000..d03661c --- /dev/null +++ b/tests/SwooleRequestTest.php @@ -0,0 +1,47 @@ +markTestSkipped('The Swoole extension is required for this test.'); + } + + /** @var \Swoole\Http\Request $swooleRequest */ + $swooleRequest = new \Swoole\Http\Request(); + $swooleRequest->header = []; + + $this->request = new Request($swooleRequest); + } + + public function tearDown(): void + { + $this->request = null; + } + + public function testCanGetScalarHeaders(): void + { + $this->request?->getSwooleRequest()->header = [ + 'x-replaced-path' => '/gateway', + ]; + + $this->assertEquals('/gateway', $this->request?->getHeader('x-replaced-path')); + } + + public function testCanNormalizeArrayHeaders(): void + { + $this->request?->getSwooleRequest()->header = [ + 'x-replaced-path' => ['/client', '/gateway'], + ]; + + $this->assertEquals('/gateway', $this->request?->getHeader('x-replaced-path')); + } +}