blob: fac9552f7854c3091f78dc32d2777cc4de7ec8a1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<?php
namespace Studip\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
class TrailingSlash
{
public function __construct(protected ResponseFactoryInterface $responseFactory)
{
}
/**
* Handle the incoming request.
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() === 'GET' && $this->responseFactory) {
$uri = $request->getUri();
$path = $this->normalize($uri->getPath());
if ($uri->getPath() !== $path) {
return $this->responseFactory->createResponse(301)
->withHeader('Location', (string) $uri->withPath($path));
}
}
return $handler->handle($request);
}
private function normalize(string $path): string
{
if ($path === '') {
return '/';
}
if (strlen($path) > 1) {
return rtrim($path, '/');
}
return $path;
}
}
|