trailingSlash = $trailingSlash; } /** * Whether returns a 301 response to the new path. */ public function redirect(ResponseFactoryInterface $responseFactory): self { $this->responseFactory = $responseFactory; return $this; } /** * Process a request and return a response. */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $uri = $request->getUri(); $path = $this->normalize($uri->getPath()); if (isset($this->responseFactory) && ($uri->getPath() !== $path)) { return $this->responseFactory->createResponse(301) ->withHeader('Location', $path); } return $handler->handle($request->withUri($uri->withPath($path))); } /** * Normalize the trailing slash. */ private function normalize(string $path): string { if ($path === '') { return '/'; } if (str_contains($path, '/api/')) { return $path; } if (strlen($path) > 1) { if ($this->trailingSlash) { if (substr($path, -1) !== '/' && pathinfo($path, PATHINFO_EXTENSION) === '') { return $path . '/'; } } else { return rtrim($path, '/'); } } return $path; } }