Completed
Push — master ( 9f10b5...c8ace5 )
by Alex
02:13
created

RequestExtension::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Asmaster\EquipTwig\Extension;
4
5
class RequestExtension extends \Twig_Extension
6
{
7
    use ServerRequestTrait;
8
9
    /**
10
     * @return string The extension name
11
     */
12
    public function getName()
13
    {
14
        return 'request';
15
    }
16
17
    public function getFunctions()
18
    {
19
        return [
20
            new \Twig_SimpleFunction('absolute_url', [$this, 'generateAbsoluteUrl'])
21
        ];
22
    }
23
24
    /**
25
     * @param string $path
26
     * @return string
27
     */
28
    public function generateAbsoluteUrl($path)
29
    {
30
        if ($this->isNetworkPath($path)) {
31
            return $path;
32
        }
33
34
        $uri = $this->request->getUri();
35
36
        $host = $uri->getHost();
37
        if ('' === $host) {
38
            return $path;
39
        }
40
41
        if (null !== $uri->getPort()) {
42
            $host .= ':'.$uri->getPort();
43
        }
44
45
        if (! $this->hasLeadingSlash($path)) {
46
            $path = rtrim($uri->getPath(), '/').'/'.$path;
47
        }
48
49
        return $uri->getScheme().'://'.$host.$path;
50
    }
51
52
    /**
53
     * @param string $path
54
     * @return bool
55
     */
56
    private function isNetworkPath($path)
57
    {
58
        return false !== strpos($path, '://') || '//' === substr($path, 0, 2);
59
    }
60
61
    /**
62
     * @param string $path
63
     * @return bool
64
     */
65
    private function hasLeadingSlash($path)
66
    {
67
        return isset($path[0]) && '/' === $path[0];
68
    }
69
}
70