Add CorsOptions test

This commit is contained in:
Alejandro Celaya
2025-07-16 08:29:57 +02:00
parent 1d96cc0279
commit 3369afe22c
3 changed files with 43 additions and 1 deletions

View File

@@ -10,6 +10,11 @@ use function in_array;
use const ARRAY_FILTER_USE_KEY;
/**
* @template T
* @param T $value
* @param T[] $array
*/
function contains(mixed $value, array $array): bool
{
return in_array($value, $array, strict: true);

View File

@@ -43,7 +43,7 @@ final readonly class CorsOptions
return $response->withHeader('Access-Control-Allow-Origin', '*');
}
$requestOrigin = $request->getHeader('Origin');
$requestOrigin = $request->getHeaderLine('Origin');
if (
// The special <origin> value means we should allow requests from the origin set in the request's Origin
// header

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\Config\Options;
use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Core\Config\Options\CorsOptions;
class CorsOptionsTest extends TestCase
{
#[Test]
#[TestWith(['*', '*', '*'])]
#[TestWith(['<origin>', '<origin>', 'https://example.com'])]
#[TestWith(['foo,bar, baz ', ['foo', 'bar', 'baz'], ''])]
#[TestWith(['foo,bar,https://example.com', ['foo', 'bar', 'https://example.com'], 'https://example.com'])]
public function expectedAccessControlAllowOriginIsSet(
string $allowOrigins,
string|array $expectedAllowOrigins,
string $expectedAllowOriginsHeader,
): void {
$options = new CorsOptions($allowOrigins);
self::assertEquals($expectedAllowOrigins, $options->allowOrigins);
self::assertEquals(
$expectedAllowOriginsHeader,
$options->responseWithAllowOrigin(
ServerRequestFactory::fromGlobals()->withHeader('Origin', 'https://example.com'),
new Response()
)->getHeaderLine('Access-Control-Allow-Origin'),
);
}
}