RelativePathGenerator::__invoke()   C
last analyzed

Complexity

Conditions 8
Paths 10

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 17
nc 10
nop 2
1
<?php
2
3
namespace AlexMasterov\TwigExtension;
4
5
use Psr\Http\Message\UriInterface;
6
7
final class RelativePathGenerator
8
{
9
    /**
10
     * @param UriInterface $uri
11
     * @param string $path
12
     *
13
     * @return string
14
     */
15
    public function __invoke(UriInterface $uri, $path)
16
    {
17
        $basePath = $uri->getPath();
18
        if ($path === $basePath) {
19
            return '';
20
        }
21
22
        $baseParts = explode('/', $basePath, -1);
23
        $pathParts = explode('/', $path);
24
25
        foreach ($baseParts as $i => $segment) {
26
            if (isset($pathParts[$i]) && $segment === $pathParts[$i]) {
27
                unset($baseParts[$i], $pathParts[$i]);
28
            } else {
29
                break;
30
            }
31
        }
32
33
        $path = str_repeat('../', count($baseParts)) . implode('/', $pathParts);
34
35
        if (empty($path)) {
36
            return './';
37
        }
38
39
        if (empty($baseParts) && false !== strpos(current($pathParts), ':')) {
40
            $path = "./{$path}";
41
        }
42
43
        return $path;
44
    }
45
}
46