Completed
Pull Request — master (#41)
by Vladimir
02:46
created

BaseUrlFunction::__invoke()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 4
b 0
f 0
nc 4
nop 2
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 3
rs 9.4285
1
<?php
2
3
namespace allejo\stakx\Twig;
4
5
use Twig_Environment;
6
7
class BaseUrlFunction
8
{
9 13
    public function __invoke (Twig_Environment $env, $assetPath)
10
    {
11 13
        $globals = $env->getGlobals();
12 13
        $assetPath = $this->guessAssetPath($assetPath);
13
14
        // @TODO 1.0.0 Remove support for 'base' as it's been deprecated
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
15 13
        $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl'];
16
17 13
        $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/';
18 13
        $url = $this->trimSlashes($assetPath);
19
20 13
        return ($baseURL . $url);
21
    }
22
23
    public static function get ()
24
    {
25
        return new \Twig_SimpleFunction('url', new self(), array(
26
            'needs_environment' => true
27
        ));
28
    }
29
30 13
    private function guessAssetPath ($assetPath)
31
    {
32 13
        if (is_array($assetPath) || ($assetPath instanceof \ArrayAccess))
33
        {
34 4
            return (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/';
35
        }
36 9
        else if (is_null($assetPath))
37
        {
38 1
            return '/';
39
        }
40
41 8
        return $assetPath;
42
    }
43
44 13
    private function trimSlashes ($url)
45
    {
46 13
        $url = ltrim($url, '/');
47
48 13
        if (!empty($url) && $url[strlen($url) - 1] == '/')
49
        {
50 4
            return rtrim($url, '/') . '/';
51
        }
52
53 9
        return $url;
54
    }
55
}