Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions src/http/src/Cors.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
57 changes: 57 additions & 0 deletions tests/Http/CorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Hypervel\Tests\Http;

use Hyperf\HttpMessage\Base\Response;
use Hypervel\Http\Cors;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
Expand Down Expand Up @@ -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'));
}
}