From deacd0dfc195bca41af631114804d29937337cd8 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Wed, 17 Jan 2024 02:11:31 +0900 Subject: . --- services/app/src/Middlewares/TrailingSlash.php | 113 +++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 services/app/src/Middlewares/TrailingSlash.php (limited to 'services/app/src/Middlewares/TrailingSlash.php') diff --git a/services/app/src/Middlewares/TrailingSlash.php b/services/app/src/Middlewares/TrailingSlash.php new file mode 100644 index 0000000..cd0f333 --- /dev/null +++ b/services/app/src/Middlewares/TrailingSlash.php @@ -0,0 +1,113 @@ +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; + } +} -- cgit v1.2.3-70-g09d2