RelativePathGenerator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 1
dl 0
loc 39
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C __invoke() 0 30 8
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