From 3369afe22cdaf7983e41b91e90572a4ec1b90aef Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Wed, 16 Jul 2025 08:29:57 +0200 Subject: [PATCH] Add CorsOptions test --- module/Core/functions/array-utils.php | 5 +++ .../Core/src/Config/Options/CorsOptions.php | 2 +- .../test/Config/Options/CorsOptionsTest.php | 37 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 module/Core/test/Config/Options/CorsOptionsTest.php diff --git a/module/Core/functions/array-utils.php b/module/Core/functions/array-utils.php index d68851d8..3e0010a2 100644 --- a/module/Core/functions/array-utils.php +++ b/module/Core/functions/array-utils.php @@ -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); diff --git a/module/Core/src/Config/Options/CorsOptions.php b/module/Core/src/Config/Options/CorsOptions.php index fbf191ee..f4a23139 100644 --- a/module/Core/src/Config/Options/CorsOptions.php +++ b/module/Core/src/Config/Options/CorsOptions.php @@ -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 value means we should allow requests from the origin set in the request's Origin // header diff --git a/module/Core/test/Config/Options/CorsOptionsTest.php b/module/Core/test/Config/Options/CorsOptionsTest.php new file mode 100644 index 00000000..cfed36d7 --- /dev/null +++ b/module/Core/test/Config/Options/CorsOptionsTest.php @@ -0,0 +1,37 @@ +', '', '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'), + ); + } +}