aboutsummaryrefslogtreecommitdiff
path: root/lib/middleware/TrailingSlash.php
blob: 2cc2292bb14b9d984974a3a33e9016e259ed8e31 (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
48
<?php

namespace Studip\Middleware;

use Closure;
use Psr\Http\Message\RequestInterface;
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(RequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $uri = $request->getUri();
        $path = $this->normalize($uri->getPath());
        if ($this->responseFactory && ($uri->getPath() !== $path)) {
            return $this->responseFactory->createResponse(301)
                ->withHeader('Location', (string) $uri->withPath($path));
        }

        $response = $handler->handle($request);

        return $response;
    }

    private function normalize(string $path): string
    {
        if ($path === '') {
            return '/';
        }

        if (strlen($path) > 1) {
            return rtrim($path, '/');
        }

        return $path;
    }
}