Passed
Push — master ( 980196...15eb80 )
by Fran
05:15
created

AssetsParser   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 161
Duplicated Lines 0 %

Test Coverage

Coverage 61.29%

Importance

Changes 9
Bugs 0 Features 0
Metric Value
wmc 25
eloc 65
c 9
b 0
f 0
dl 0
loc 161
ccs 38
cts 62
cp 0.6129
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A setHash() 0 5 2
A calculateResourcePathname() 0 13 3
B addFile() 0 13 7
A extractCssLineResource() 0 16 5
A printHtml() 0 11 4
A compile() 0 15 3
A __construct() 0 6 1
1
<?php
2
3
namespace PSFS\base\extension;
4
5
use PSFS\base\config\Config;
6
use PSFS\base\exception\ConfigException;
7
use PSFS\base\extension\traits\CssTrait;
8
use PSFS\base\extension\traits\JsTrait;
9
use PSFS\base\Logger;
10
use PSFS\base\Request;
11
use PSFS\base\Template;
12
use PSFS\base\types\helpers\GeneratorHelper;
13
14
/**
15
 * Class AssetsParser
16
 * @package PSFS\base\extension
17
 */
18
class AssetsParser
19
{
20
    use CssTrait;
21
    use JsTrait;
22
23
    /**
24
     * @var array
25
     */
26
    protected $files = [];
27
    /**
28
     * @var string
29
     */
30
    protected $hash;
31
    /**
32
     * @var array
33
     */
34
    protected $compiledFiles = [];
35
    /**
36
     * @var string
37
     */
38
    protected $type;
39
    /**
40
     * @var array
41
     */
42
    protected $domains = [];
43
    /**
44
     * @var string
45
     */
46
    private $cdnPath = null;
47
48
    /**
49
     * Constructor por defecto
50
     *
51
     * @param string $type
52
     */
53 1
    public function __construct($type = 'js')
54
    {
55 1
        $this->type = $type;
56 1
        $this->path = WEB_DIR . DIRECTORY_SEPARATOR;
57 1
        $this->domains = Template::getDomains(true);
58 1
        $this->cdnPath = Config::getParam('resources.cdn.url', Request::getInstance()->getRootUrl());
59 1
    }
60
61
    /**
62
     * Método que añade un nuevo fichero al proceso de generación de los assets
63
     * @param $filename
64
     * @return AssetsParser
65
     * @internal param string $type
66
     */
67 1
    public function addFile($filename)
68
    {
69 1
        if (file_exists($this->path . $filename) && preg_match('/\.' . $this->type . '$/i', $filename)) {
70
            $this->files[] = $filename;
71 1
        } elseif (!empty($this->domains)) {
72 1
            foreach ($this->domains as $domain => $paths) {
73 1
                $domainFilename = str_replace($domain, $paths["public"], $filename);
74 1
                if (file_exists($domainFilename) && preg_match('/\.' . $this->type . '$/i', $domainFilename)) {
75 1
                    $this->files[] = $domainFilename;
76
                }
77
            }
78
        }
79 1
        return $this;
80
    }
81
82
    /**
83
     * Método que establece el hash con el que compilar los assets
84
     * @param string $hash
85
     *
86
     * @return AssetsParser
87
     */
88 1
    public function setHash($hash)
89
    {
90 1
        $cache = Config::getParam('cache.var', '');
91 1
        $this->hash = $hash . (strlen($cache) ? '.' : '') . $cache;
92 1
        return $this;
93
    }
94
95
    /**
96
     * Método que procesa los ficheros solicitados en función del modo de ejecución
97
     * @return AssetsParser
98
     * @internal param string $type
99
     * @throws ConfigException
100
     * @throws \PSFS\base\exception\GeneratorException
101
     */
102 1
    public function compile()
103
    {
104
        //Unificamos ficheros para que no se retarde mucho el proceso
105 1
        $this->files = array_unique($this->files);
106 1
        switch ($this->type) {
107
            default:
108 1
            case "js":
109 1
                $this->compileJs($this->files, $this->path, $this->hash, $this->compiledFiles);
110 1
                break;
111 1
            case "css":
112 1
                $this->compileCss($this->path, $this->hash);
113 1
                break;
114
        }
115
116 1
        return $this;
117
    }
118
119
    /**
120
     * Método que imprime el resultado de la generación de los assets
121
     */
122 1
    public function printHtml()
123
    {
124 1
        $baseUrl = $this->cdnPath ?: '';
125 1
        switch ($this->type) {
126
            default:
127 1
            case "js":
128 1
                $this->printJs($this->compiledFiles, $baseUrl, $this->hash);
129 1
                break;
130 1
            case "css":
131 1
                $this->printCss($this->compiledFiles, $baseUrl, $this->hash);
132 1
                break;
133
        }
134 1
    }
135
136
    /**
137
     * Método que calcula el path completo a copiar un recurso
138
     * @param string $filenamePath
139
     * @param string[] $source
140
     * @return string
141
     */
142
    protected static function calculateResourcePathname($filenamePath, $source)
143
    {
144
        $sourceFile = preg_replace("/'/", "", $source[1]);
145
        if (preg_match('/\#/', $sourceFile)) {
146
            $sourceFile = explode("#", $sourceFile);
147
            $sourceFile = $sourceFile[0];
148
        }
149
        if (preg_match('/\?/', $sourceFile)) {
150
            $sourceFile = explode("?", $sourceFile);
151
            $sourceFile = $sourceFile[0];
152
        }
153
        $orig = realpath(dirname($filenamePath) . DIRECTORY_SEPARATOR . $sourceFile);
154
        return $orig;
155
    }
156
157
    /**
158
     * Método que extrae el recurso css de una línea de estilos css
159
     * @param $handle
160
     * @param string $filenamePath
161
     * @throws \PSFS\base\exception\GeneratorException
162
     */
163
    public static function extractCssLineResource($handle, $filenamePath)
164
    {
165
        $line = fgets($handle);
166
        $urls = array();
167
        if (preg_match_all('#url\((.*?)\)#', $line, $urls, PREG_SET_ORDER)) {
168
            foreach ($urls as $source) {
169
                $orig = self::calculateResourcePathname($filenamePath, $source);
170
                if(!empty($orig)) {
171
                    $orig_part = preg_split("/Public/i", $orig);
172
                    $dest = WEB_DIR . $orig_part[1];
173
                    GeneratorHelper::createDir(dirname($dest));
174
                    if (@copy($orig, $dest) === false) {
175
                        throw new ConfigException("Can't copy " . $orig . " to " . $dest);
176
                    }
177
                } else {
178
                    Logger::log($filenamePath . ' has an empty origin with the url ' . $source, LOG_WARNING);
179
                }
180
            }
181
        }
182
    }
183
184
}
185