Asset   A
last analyzed

↳ Parent: Project

Coupling/Cohesion

Components 1
Dependencies 1

Complexity

Total Complexity 7

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 74
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A register() 0 4 1
B cachedAssetUrl() 0 27 5
1
<?php
2
3
namespace League\Plates\Extension;
4
5
use League\Plates\Engine;
6
use League\Plates\Template\Template;
7
use LogicException;
8
9
/**
10
 * Extension that adds the ability to create "cache busted" asset URLs.
11
 */
12
class Asset implements ExtensionInterface
13
{
14
    /**
15
     * Instance of the current template.
16
     * @var Template
17
     */
18
    public $template;
19
20
    /**
21
     * Path to asset directory.
22
     * @var string
23
     */
24
    public $path;
25
26
    /**
27
     * Enables the filename method.
28
     * @var boolean
29
     */
30
    public $filenameMethod;
31
32
    /**
33
     * Create new Asset instance.
34
     * @param string  $path
35
     * @param boolean $filenameMethod
36
     */
37 28
    public function __construct($path, $filenameMethod = false)
38
    {
39 28
        $this->path = rtrim($path, '/');
40 28
        $this->filenameMethod = $filenameMethod;
41 28
    }
42
43
    /**
44
     * Register extension function.
45
     * @param Engine $engine
46
     * @return null
47
     */
48 8
    public function register(Engine $engine)
49
    {
50 8
        $engine->registerFunction('asset', array($this, 'cachedAssetUrl'));
51 8
    }
52
53
    /**
54
     * Create "cache busted" asset URL.
55
     * @param  string $url
56
     * @return string
57
     */
58 16
    public function cachedAssetUrl($url)
59
    {
60 16
        $filePath = $this->path . '/' .  ltrim($url, '/');
61
62 16
        if (!file_exists($filePath)) {
63 4
            throw new LogicException(
64 4
                'Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.'
65 2
            );
66
        }
67
68 12
        $lastUpdated = filemtime($filePath);
69 12
        $pathInfo = pathinfo($url);
70
71 12
        if ($pathInfo['dirname'] === '.') {
72 8
            $directory = '';
73 10
        } elseif ($pathInfo['dirname'] === '/') {
74 4
            $directory = '/';
75 2
        } else {
76 4
            $directory = $pathInfo['dirname'] . '/';
77
        }
78
79 12
        if ($this->filenameMethod) {
80 4
            return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension'];
81
        }
82
83 8
        return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated;
84
    }
85
}
86