Completed
Push — components-poc ( 6ce8f4...e1010e )
by
unknown
13:39
created

Asset   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 74
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
A 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
    public function __construct($path, $filenameMethod = false)
38
    {
39
        $this->path = rtrim($path, '/');
40
        $this->filenameMethod = $filenameMethod;
41
    }
42
43
    /**
44
     * Register extension function.
45
     * @param Engine $engine
46
     * @return null
47
     */
48
    public function register(Engine $engine)
49
    {
50
        $engine->registerFunction('asset', array($this, 'cachedAssetUrl'));
51
    }
52
53
    /**
54
     * Create "cache busted" asset URL.
55
     * @param  string $url
56
     * @return string
57
     */
58
    public function cachedAssetUrl($url)
59
    {
60
        $filePath = $this->path . '/' .  ltrim($url, '/');
61
62
        if (!file_exists($filePath)) {
63
            throw new LogicException(
64
                'Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.'
65
            );
66
        }
67
68
        $lastUpdated = filemtime($filePath);
69
        $pathInfo = pathinfo($url);
70
71
        if ($pathInfo['dirname'] === '.') {
72
            $directory = '';
73
        } elseif ($pathInfo['dirname'] === DIRECTORY_SEPARATOR) {
74
            $directory = '/';
75
        } else {
76
            $directory = $pathInfo['dirname'] . '/';
77
        }
78
79
        if ($this->filenameMethod) {
80
            return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension'];
81
        }
82
83
        return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated;
84
    }
85
}
86