origin)) { $this->origin = explode(',', $this->origin); } } public function renderHeader(ServerRequestInterface $request) : void { $matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin); if (! $matched) { return; } $render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e)); header('Access-Control-Allow-Origin: ' . $matched); header(sprintf('Access-Control-Allow-Methods: %s', $render($this->methods))); header(sprintf('Access-Control-Allow-Headers: %s', $render($this->headers))); header('Access-Control-Allow-Credentials: ' . ($this->allowCredentials ? 'true' : 'false')); } public function fromResponse(ResponseInterface $response, bool $emptyResponse = false) : ResponseInterface { $matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin); if (! $matched) { return $response; } $render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e)); $response = $response ->withHeader('Access-Control-Allow-Origin', $matched) ->withHeader('Access-Control-Allow-Methods', $render($this->methods)) ->withHeader('Access-Control-Allow-Headers', $render($this->headers)) ->withHeader('Access-Control-Allow-Credentials', $this->allowCredentials ? 'true' : 'false'); if ($emptyResponse) { $response = $response->withBody(Stream::fromMemory())->withStatus(200); } return $response; } function matchOrigin(?string $origin, string|array $allowList): ?string { if ($origin === null || $origin === '') { return null; } foreach ((array) $allowList as $rule) { if ($rule === '*') { return '*'; } // Regex rule: "/.../" if (is_string($rule) && strlen($rule) >= 2 && $rule[0] === '/' && substr($rule, -1) === '/') { if (@preg_match($rule, $origin) === 1) { return $origin; } continue; } // Exact match if (is_string($rule) && hash_equals($rule, $origin)) { return $origin; } } return null; } }