Completed
Push — master ( 9566ca...29bf5e )
by Vladimir
02:08
created

BaseUrlFunction::isExternalUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Templating\Twig\Extension;
9
10
use allejo\stakx\Document\JailedDocument;
11
use allejo\stakx\Document\RepeaterPageView;
12
use allejo\stakx\Service;
13
use Twig_Environment;
14
15
class BaseUrlFunction extends AbstractTwigExtension implements TwigFunctionInterface
16
{
17
    private $site;
18
19 22
    public function __invoke(Twig_Environment $env, $assetPath, $absolute = false, $params = [])
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
20
    {
21 22
        if ($this->isExternalUrl($assetPath))
22
        {
23 4
            return $assetPath;
24
        }
25
26 18
        $globals = $env->getGlobals();
27 18
        $this->site = $globals['site'];
28
29 18
        $url = $this->getUrl($absolute);
30 18
        $baseURL = $this->getBaseUrl();
31 18
        $permalink = $this->guessAssetPath($assetPath, $params);
32
33 18
        return $this->buildPermalink($url, $baseURL, $permalink);
34
    }
35
36 22
    public static function get()
37
    {
38 22
        return new \Twig_SimpleFunction('url', new self(), [
39 22
            'needs_environment' => true,
40
        ]);
41
    }
42
43 18
    private function getUrl($absolute)
44
    {
45 18
        $url = '/';
46
47 18
        if (!$absolute)
48
        {
49 16
            return $url;
50
        }
51
52 2
        if (isset($this->site['url']))
53
        {
54 2
            $url = $this->site['url'];
55
        }
56
57 2
        return ltrim($url, '/');
58
    }
59
60 18
    private function getBaseUrl()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
61
    {
62 18
        $base = '';
63
64 18
        if (isset($this->site['baseurl']))
65
        {
66 15
            $base = $this->site['baseurl'];
67
        }
68 3
        elseif (isset($this->site['base']))
69
        {
70
            $base = $this->site['base'];
71
        }
72
73 18
        return $base;
74
    }
75
76 18
    private function guessAssetPath($assetPath, $params)
77
    {
78 18
        if ($assetPath instanceof JailedDocument && $assetPath->_coreInstanceOf(RepeaterPageView::class))
79
        {
80
            /** @var RepeaterPageView $assetPath */
81
            return ($link = $assetPath->_getPermalinkWhere($params)) ? $link : '/';
82
        }
83 18
        elseif (is_array($assetPath) || ($assetPath instanceof \ArrayAccess))
84
        {
85 4
            return (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/';
86
        }
87 14
        elseif (is_null($assetPath))
88
        {
89 1
            return '/';
90
        }
91 13
        elseif ($assetPath instanceof \SplFileInfo)
92
        {
93
            return str_replace(Service::getWorkingDirectory(), '', $assetPath);
94
        }
95
96 13
        return $assetPath;
97
    }
98
99
    /**
100
     * Match external URLs.
101
     *
102
     * If the string contains an `://`, then it's guessed to be an external URL.
103
     *
104
     * @param string|mixed $str
105
     *
106
     * @return bool True if the given string is guessed to be an external URL.
107
     */
108 22
    private function isExternalUrl($str)
109
    {
110 22
        if (!is_string($str))
111
        {
112 5
            return false;
113
        }
114
115 17
        return preg_match('#.+://.+#', $str) === 1;
116
    }
117
118
    /**
119
     * @see   https://stackoverflow.com/a/15575293
120
     *
121
     * @return string
122
     */
123 18 View Code Duplication
    private function buildPermalink()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
    {
125 18
        $paths = [];
126
127 18
        foreach (func_get_args() as $arg)
128
        {
129 18
            if ($arg !== '')
130
            {
131 18
                $paths[] = $arg;
132
            }
133
        }
134
135 18
        return preg_replace('#(?<!:)/+#', '/', join('/', $paths));
136
    }
137
}
138