with('CORS_ALLOWED_ORIGINS', 'https://example.com,https://another.com') ->andReturn('https://example.com,https://another.com'); $middleware = new CorsMiddleware(); $request = new ServerRequest('GET', '/')->withHeader('Origin', 'https://example.com'); $handler = $this->mockHandler(new Response(200)); $response = $middleware->process($request, $handler); $this->assertEquals('https://example.com', $response->getHeaderLine('Access-Control-Allow-Origin')); } public function testBlocksUnconfiguredOrigin(): void { Config::shouldReceive('get') ->with('CORS_ALLOWED_ORIGINS', 'https://example.com,https://another.com') ->andReturn('https://example.com,https://another.com'); $middleware = new CorsMiddleware(); $request = new ServerRequest('GET', '/')->withHeader('Origin', 'https://unauthorized.com'); $handler = $this->mockHandler(new Response(200)); $response = $middleware->process($request, $handler); $this->assertEquals('null', $response->getHeaderLine('Access-Control-Allow-Origin')); } public function testHandlesOptionsRequest(): void { Config::shouldReceive('get')->with('CORS_ALLOWED_ORIGINS', '...')->andReturn('https://example.com'); Config::shouldReceive('get')->with('CORS_ALLOW_CREDENTIALS', 'bool')->andReturn(false); Config::shouldReceive('get')->with('CORS_MAX_AGE')->andReturn('86400'); $middleware = new CorsMiddleware(); $request = new ServerRequest('OPTIONS', '/')->withHeader('Origin', 'https://example.com'); $handler = $this->mockHandler(new Response(200)); $response = $middleware->process($request, $handler); $this->assertEquals(204, $response->getStatusCode()); $this->assertEquals('86400', $response->getHeaderLine('Access-Control-Max-Age')); } public function testAddsAllowCredentialsHeader(): void { Config::shouldReceive('get')->with('CORS_ALLOWED_ORIGINS', '...')->andReturn('https://example.com'); Config::shouldReceive('get')->with('CORS_ALLOW_CREDENTIALS', 'bool')->andReturn(true); $middleware = new CorsMiddleware(); $request = new ServerRequest('GET', '/')->withHeader('Origin', 'https://example.com'); $handler = $this->mockHandler(new Response(200)); $response = $middleware->process($request, $handler); $this->assertEquals('true', $response->getHeaderLine('Access-Control-Allow-Credentials')); } private function mockHandler(Response $response): RequestHandlerInterface { return new class($response) implements RequestHandlerInterface { private Response $response; public function __construct(Response $response) { $this->response = $response; } public function handle(\Psr\Http\Message\ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface { return $this->response; } }; } }