TrailingSlash::__invoke()   C
last analyzed

Complexity

Conditions 8
Paths 10

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 14
nc 10
nop 3
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * Middleware to add or remove the trailing slash.
11
 */
12
class TrailingSlash
13
{
14
    use Utils\RedirectTrait;
15
16
    /**
17
     * @var bool Add or remove the slash
18
     */
19
    private $addSlash;
20
21
    /**
22
     * Configure whether add or remove the slash.
23
     *
24
     * @param bool $addSlash
25
     */
26
    public function __construct($addSlash = false)
27
    {
28
        $this->addSlash = (bool) $addSlash;
29
    }
30
31
    /**
32
     * Execute the middleware.
33
     *
34
     * @param ServerRequestInterface $request
35
     * @param ResponseInterface      $response
36
     * @param callable               $next
37
     *
38
     * @return ResponseInterface
39
     */
40
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
41
    {
42
        $uri = $request->getUri();
43
        $path = $uri->getPath();
44
45
        //Add/remove slash
46
        if (strlen($path) > 1) {
47
            if ($this->addSlash) {
48
                if (substr($path, -1) !== '/' && !pathinfo($path, PATHINFO_EXTENSION)) {
49
                    $path .= '/';
50
                }
51
            } else {
52
                $path = rtrim($path, '/');
53
            }
54
        } elseif ($path === '') {
55
            $path = '/';
56
        }
57
58
        //redirect
59
        if ($this->redirectStatus !== false && ($uri->getPath() !== $path)) {
60
            return $this->getRedirectResponse($request, $uri->withPath($path), $response);
61
        }
62
63
        return $next($request->withUri($uri->withPath($path)), $response);
64
    }
65
}
66