TrailingSlashMiddleware::normalize()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 3
b 0
f 0
nc 4
nop 1
dl 0
loc 16
ccs 9
cts 9
cp 1
crap 5
rs 9.6111
1
<?php
2
declare(strict_types=1);
3
4
namespace Ctw\Middleware\TrailingSlashMiddleware;
5
6
use Ctw\Http\HttpStatus;
7
use Middlewares\Utils\Factory;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
class TrailingSlashMiddleware extends AbstractTrailingSlashMiddleware
13
{
14
    /**
15
     * @var string
16
     */
17
    private const HEADER = 'Location';
18
19 6
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
20
    {
21 6
        $config   = $this->getConfig();
22 6
        $uri      = $request->getUri();
23 6
        $response = $handler->handle($request);
24
25 6
        if (isset($config['path_disable'])) {
26
            foreach ($config['path_disable'] as $path) {
27
                if (str_starts_with($uri->getPath(), $path)) {
28
                    return $response;
29
                }
30
            }
31
        }
32
33 6
        $path = $this->normalize($uri->getPath());
34
35 6
        if ($path === $uri->getPath()) {
36 2
            return $response;
37
        }
38
39 4
        $location = $uri->withPath($path)
40 4
            ->__toString();
41 4
        $factory  = Factory::getResponseFactory();
42 4
        $response = $factory->createResponse(HttpStatus::STATUS_MOVED_PERMANENTLY);
43
44 4
        return $response->withHeader(self::HEADER, $location);
45
    }
46
47 6
    private function normalize(string $path): string
48
    {
49 6
        $slash = '/';
50
51 6
        if ('' === $path) {
52 2
            return $slash;
53
        }
54
55 4
        if (1 < strlen($path)) {
56 4
            $extension = pathinfo($path, PATHINFO_EXTENSION);
57 4
            if ($slash !== substr($path, -1) && '' === $extension) {
58 2
                return $path . $slash;
59
            }
60
        }
61
62 2
        return $path;
63
    }
64
}
65