diff --git a/src/http/src/Cors.php b/src/http/src/Cors.php index 7b7c14d7d..0fc7b6ba4 100644 --- a/src/http/src/Cors.php +++ b/src/http/src/Cors.php @@ -290,11 +290,7 @@ public function varyHeader(ResponseInterface $response, string $header): Respons } else { $varyHeaders = $response->getHeader('Vary'); if (! in_array($header, $varyHeaders, true)) { - if (count($varyHeaders) === 1) { - $response = $response->withHeader('Vary', ((string) $varyHeaders[0]) . ', ' . $header); - } else { - $response->withHeader($header, false); - } + $response = $response->withHeader('Vary', implode(', ', $varyHeaders) . ', ' . $header); } } diff --git a/tests/Http/CorsTest.php b/tests/Http/CorsTest.php index 40a5a3db8..3990429e4 100644 --- a/tests/Http/CorsTest.php +++ b/tests/Http/CorsTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Http; +use Hyperf\HttpMessage\Base\Response; use Hypervel\Http\Cors; use PHPUnit\Framework\TestCase; use ReflectionClass; @@ -247,4 +248,60 @@ private function getOptionsFromService(Cors $service): array /** @var CorsNormalizedOptions $options */ return $options; } + + public function testVaryHeaderAddsHeaderWhenNoneExists(): void + { + $cors = new Cors(); + $response = new Response(); + + $result = $cors->varyHeader($response, 'Origin'); + + $this->assertSame(['Origin'], $result->getHeader('Vary')); + } + + public function testVaryHeaderAppendsToExistingSingleHeader(): void + { + $cors = new Cors(); + $response = (new Response())->withHeader('Vary', 'Accept-Encoding'); + + $result = $cors->varyHeader($response, 'Origin'); + + $this->assertSame(['Accept-Encoding, Origin'], $result->getHeader('Vary')); + } + + public function testVaryHeaderDoesNotDuplicateExistingHeader(): void + { + $cors = new Cors(); + $response = (new Response())->withHeader('Vary', 'Origin'); + + $result = $cors->varyHeader($response, 'Origin'); + + $this->assertSame(['Origin'], $result->getHeader('Vary')); + } + + public function testVaryHeaderHandlesMultipleExistingHeaders(): void + { + $cors = new Cors(); + // PSR-7 allows multiple header values as array elements + $response = (new Response()) + ->withHeader('Vary', 'Accept-Encoding') + ->withAddedHeader('Vary', 'Accept-Language'); + + $result = $cors->varyHeader($response, 'Origin'); + + $this->assertSame(['Accept-Encoding, Accept-Language, Origin'], $result->getHeader('Vary')); + } + + public function testVaryHeaderDoesNotDuplicateWhenInMultipleHeaders(): void + { + $cors = new Cors(); + $response = (new Response()) + ->withHeader('Vary', 'Accept-Encoding') + ->withAddedHeader('Vary', 'Origin'); + + $result = $cors->varyHeader($response, 'Origin'); + + // Should not add Origin again since it's already present + $this->assertSame(['Accept-Encoding', 'Origin'], $result->getHeader('Vary')); + } }