Completed
Push — master ( a0318a...ed4471 )
by Oscar
02:30
created

BasePathTrait::getBasePath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4286
cc 3
eloc 4
nc 3
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
/**
6
 * Utilities used by middlewares with basePath options.
7
 */
8
trait BasePathTrait
9
{
10
    private $basePath = '';
11
12
    /**
13
     * Set the basepath used in the request.
14
     *
15
     * @param string $basePath
16
     *
17
     * @return self
18
     */
19
    public function basePath($basePath)
20
    {
21
        $this->basePath = $basePath;
22
23
        return $this;
24
    }
25
26
    /**
27
     * Removes the basepath from a path.
28
     *
29
     * @param string $path
30
     *
31
     * @return string
32
     */
33
    private function getBasePath($path)
34
    {
35
        if ($this->testBasePath($path)) {
36
            return substr($path, strlen($this->basePath)) ?: '';
37
        }
38
39
        return $path;
40
    }
41
42
    /**
43
     * Tests the basepath and returns whether the path matches.
44
     *
45
     * @param string $path
46
     *
47
     * @return bool
48
     */
49
    private function testBasePath($path)
50
    {
51
        if ($path === '') {
52
            $path = '/';
53
        }
54
55
        return $this->basePath === '' || strpos($path, $this->basePath) === 0;
56
    }
57
}
58