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

RequestExtension::generateRelativeUrl()   D

Complexity

Conditions 10
Paths 11

Size

Total Lines 40
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 40
rs 4.8196
cc 10
eloc 22
nc 11
nop 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A RequestExtension::hasLeadingSlash() 0 4 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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