Completed
Push — master ( 00ed35...63fbb3 )
by Oscar
10:20
created

TrailingSlash::addSlash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 6
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\RequestInterface;
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\BasePathTrait;
15
    use Utils\RedirectTrait;
16
17
    /**
18
     * @var bool Add or remove the slash
19
     */
20
    private $addSlash;
21
22
    /**
23
     * Configure whether add or remove the slash.
24
     *
25
     * @param bool $addSlash
26
     */
27
    public function __construct($addSlash = false)
28
    {
29
        $this->addSlash = (boolean) $addSlash;
30
    }
31
32
    /**
33
     * Execute the middleware.
34
     *
35
     * @param RequestInterface  $request
36
     * @param ResponseInterface $response
37
     * @param callable          $next
38
     *
39
     * @return ResponseInterface
40
     */
41
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
42
    {
43
        $uri = $request->getUri();
44
        $path = $uri->getPath();
45
46
        //Test basePath
47
        if (!$this->testBasePath($path)) {
48
            return $next($request, $response);
49
        }
50
51
        //Add/remove slash
52
        if ($this->addSlash) {
53
            if (strlen($path) > 1 && substr($path, -1) !== '/' && !pathinfo($path, PATHINFO_EXTENSION)) {
54
                $path .= '/';
55
            }
56 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
57
            if (strlen($path) > 1 && substr($path, -1) === '/') {
58
                $path = substr($path, 0, -1);
59
            }
60
        }
61
62
        //Ensure the path has one "/"
63
        if (empty($path) || $path === $this->basePath) {
64
            $path .= '/';
65
        }
66
67
        //redirect
68
        if (is_int($this->redirectStatus) && ($uri->getPath() !== $path)) {
69
            return self::getRedirectResponse($this->redirectStatus, $uri->withPath($path), $response);
70
        }
71
72
        return $next($request->withUri($uri->withPath($path)), $response);
73
    }
74
}
75