1 | <?php |
||
8 | class Psr7UriExtension extends Twig_Extension |
||
9 | { |
||
10 | use ServerRequestTrait; |
||
11 | |||
12 | /** |
||
13 | * @return string The extension name |
||
14 | */ |
||
15 | 1 | public function getName() |
|
19 | |||
20 | 1 | public function getFunctions() |
|
27 | |||
28 | /** |
||
29 | * @param string $path |
||
30 | * |
||
31 | * @return string |
||
32 | */ |
||
33 | 10 | public function generateAbsoluteUrl($path) |
|
56 | |||
57 | /** |
||
58 | * @param string $path |
||
59 | * |
||
60 | * @return string |
||
61 | */ |
||
62 | 10 | public function generateRelativePath($path) |
|
63 | { |
||
64 | 10 | if ($this->isNetworkPath($path) || !$this->hasLeadingSlash($path)) { |
|
65 | 1 | return $path; |
|
66 | } |
||
67 | |||
68 | 9 | $uri = $this->request->getUri(); |
|
69 | |||
70 | 9 | $basePath = $uri->getPath(); |
|
71 | 9 | if ($basePath === $path) { |
|
72 | 1 | return ''; |
|
73 | } |
||
74 | |||
75 | 8 | $baseParts = explode('/', $basePath, -1); |
|
76 | 8 | $pathParts = explode('/', $path); |
|
77 | |||
78 | 8 | foreach ($baseParts as $i => $segment) { |
|
79 | 7 | if (isset($pathParts[$i]) && $segment === $pathParts[$i]) { |
|
80 | 7 | unset($baseParts[$i], $pathParts[$i]); |
|
81 | 7 | } else { |
|
82 | 2 | break; |
|
83 | } |
||
84 | 8 | } |
|
85 | |||
86 | 8 | $path = str_repeat('../', count($baseParts)) . implode('/', $pathParts); |
|
87 | |||
88 | 8 | if (empty($path)) { |
|
89 | 1 | return './'; |
|
90 | } |
||
91 | |||
92 | 7 | if (empty($baseParts) && false !== strpos(current($pathParts), ':')) { |
|
93 | 1 | $path = './' . $path; |
|
94 | 1 | } |
|
95 | |||
96 | 7 | return $path; |
|
97 | } |
||
98 | |||
99 | /** |
||
100 | * @param string $path |
||
101 | * |
||
102 | * @return bool |
||
103 | */ |
||
104 | 20 | protected function isNetworkPath($path) |
|
109 | |||
110 | /** |
||
111 | * @param string $path |
||
112 | * |
||
113 | * @return bool |
||
114 | */ |
||
115 | 17 | protected function hasLeadingSlash($path) |
|
119 | } |
||
120 |