Completed
Push — master ( e31cbc...a61c01 )
by Revin
02:14
created

CSS::process()   C

Complexity

Conditions 12
Paths 9

Size

Total Lines 72
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 46
CRAP Score 12.033

Importance

Changes 0
Metric Value
dl 0
loc 72
ccs 46
cts 49
cp 0.9388
rs 5.519
c 0
b 0
f 0
cc 12
eloc 42
nc 9
nop 1
crap 12.033

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * CSS.php
4
 * @author Revin Roman
5
 * @link https://rmrevin.com
6
 */
7
8
namespace rmrevin\yii\minify\components;
9
10
use yii\helpers\Html;
11
12
/**
13
 * Class CSS
14
 * @package rmrevin\yii\minify\components
15
 */
16
class CSS extends MinifyComponent
17
{
18
19 8
    public function export()
20
    {
21 8
        $cssFiles = $this->view->cssFiles;
22
23 8
        $this->view->cssFiles = [];
24
25 8
        $toMinify = [];
26
27 8 View Code Duplication
        if (!empty($cssFiles)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
28 7
            foreach ($cssFiles as $file => $html) {
29 7
                if ($this->thisFileNeedMinify($file, $html)) {
30 7
                    if ($this->view->concatCss) {
31 7
                        $toMinify[$file] = $html;
32 7
                    } else {
33
                        $this->process([$file => $html]);
34
                    }
35 7
                } else {
36 2
                    if (!empty($toMinify)) {
37 2
                        $this->process($toMinify);
38
39 2
                        $toMinify = [];
40 2
                    }
41
42 2
                    $this->view->cssFiles[$file] = $html;
43
                }
44 7
            }
45 7
        }
46
47 8
        if (!empty($toMinify)) {
48 5
            $this->process($toMinify);
49 5
        }
50
51 8
        unset($toMinify);
52 8
    }
53
54
    /**
55
     * @param array $files
56
     */
57 7
    protected function process(array $files)
58
    {
59 7
        $resultFile = $this->view->minifyPath . DIRECTORY_SEPARATOR . $this->_getSummaryFilesHash($files) . '.css';
60
61 7
        if (!file_exists($resultFile)) {
62 7
            $css = '';
63
64 7
            foreach ($files as $file => $html) {
65 7
                $path = dirname($file);
66 7
                $file = $this->getAbsoluteFilePath($file);
67
68 7
                $content = '';
69
70 7
                if (!file_exists($file)) {
71
                    \Yii::warning(sprintf('Asset file not found `%s`', $file), __METHOD__);
72 7
                } elseif (!is_readable($file)) {
73
                    \Yii::warning(sprintf('Asset file not readable `%s`', $file), __METHOD__);
74
                } else {
75 7
                    $content = file_get_contents($file);
76
                }
77
78 7
                $result = [];
79
80 7
                preg_match_all('|url\(([^)]+)\)|is', $content, $m);
81 7
                if (!empty($m[0])) {
82 7
                    foreach ($m[0] as $k => $v) {
83 7
                        if (in_array(strpos($m[1][$k], 'data:'), [0, 1], true)) {
84 7
                            continue;
85
                        }
86
87 7
                        $url = str_replace(['\'', '"'], '', $m[1][$k]);
88
89 7
                        if ($this->isUrl($url)) {
90 7
                            $result[$m[1][$k]] = $url;
91 7
                        } else {
92 7
                            $result[$m[1][$k]] = $path . '/' . $url;
93
                        }
94 7
                    }
95
96 7
                    $content = strtr($content, $result);
97 7
                }
98
99 7
                $css .= $content;
100 7
            }
101
102 7
            $this->expandImports($css);
103
104 7
            $this->removeCssComments($css);
105
106 7
            if ($this->view->minifyCss) {
107 7
                $css = (new \CSSmin())
108 7
                    ->run($css, $this->view->cssLinebreakPos);
109 7
            }
110
111 7
            $charsets = false !== $this->view->forceCharset
112 7
                ? ('@charset "' . (string)$this->view->forceCharset . '";' . "\n")
113 7
                : $this->collectCharsets($css);
114
115 7
            $imports = $this->collectImports($css);
116 7
            $fonts = $this->collectFonts($css);
117
118 7
            file_put_contents($resultFile, $charsets . $imports . $fonts . $css);
119
120 7
            if (false !== $this->view->fileMode) {
121 7
                @chmod($resultFile, $this->view->fileMode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
122 7
            }
123 7
        }
124
125 7
        $file = $this->prepareResultFile($resultFile);
126
127 7
        $this->view->cssFiles[$file] = Html::cssFile($file);
128 7
    }
129
130
    /**
131
     * @param string $code
132
     */
133 7
    protected function removeCssComments(&$code)
134
    {
135 7
        if (true === $this->view->removeComments) {
136 7
            $code = preg_replace('#/\*(?:[^*]*(?:\*(?!/))*)*\*/#', '', $code);
137 7
        }
138 7
    }
139
140
    /**
141
     * @param string $code
142
     */
143 7
    protected function expandImports(&$code)
144
    {
145 7
        if (true === $this->view->expandImports) {
146 7
            preg_match_all('|\@import\s([^;]+);|is', str_replace('&amp;', '&', $code), $m);
147
148 7
            if (!empty($m[0])) {
149 7
                foreach ($m[0] as $k => $v) {
150 7
                    $import_url = $m[1][$k];
151
152 7
                    if (!empty($import_url)) {
153 7
                        $import_content = $this->_getImportContent($import_url);
154
155 7
                        if (!empty($import_content)) {
156 7
                            $code = str_replace($m[0][$k], $import_content, $code);
157 7
                        }
158 7
                    }
159 7
                }
160 7
            }
161 7
        }
162 7
    }
163
164
    /**
165
     * @param string $code
166
     * @return string
167
     */
168
    protected function collectCharsets(&$code)
169
    {
170
        return $this->_collect($code, '|\@charset[^;]+|is', function ($string) {
171
            return $string . ';';
172
        });
173
    }
174
175
    /**
176
     * @param string $code
177
     * @return string
178
     */
179 7
    protected function collectImports(&$code)
180
    {
181
        return $this->_collect($code, '|\@import[^;]+|is', function ($string) {
182
            return $string . ';';
183 7
        });
184
    }
185
186
    /**
187
     * @param string $code
188
     * @return string
189
     */
190
    protected function collectFonts(&$code)
191
    {
192 7
        return $this->_collect($code, '|\@font-face\{[^}]+\}|is', function ($string) {
193 7
            return $string;
194 7
        });
195
    }
196
197
    /**
198
     * @param string $code
199
     * @param string $pattern
200
     * @param callable $handler
201
     * @return string
202
     */
203 7
    protected function _collect(&$code, $pattern, $handler)
204
    {
205 7
        $result = '';
206
207 7
        preg_match_all($pattern, $code, $m);
208
209 7
        foreach ($m[0] as $string) {
210 7
            $string = $handler($string);
211 7
            $code = str_replace($string, '', $code);
212
213 7
            $result .= $string . PHP_EOL;
214 7
        }
215
216 7
        return $result;
217
    }
218
219
    /**
220
     * @param string $url
221
     * @return null|string
222
     */
223 7
    protected function _getImportContent($url)
224
    {
225 7
        $result = null;
226
227 7
        if ('url(' === mb_substr($url, 0, 4)) {
228 7
            $url = str_replace(['url(\'', 'url("', 'url(', '\')', '")', ')'], '', $url);
229
230 7
            if (mb_substr($url, 0, 2) === '//') {
231 7
                $url = preg_replace('|^//|', 'http://', $url, 1);
232 7
            }
233
234 7
            if (!empty($url)) {
235 7
                if (!in_array(mb_substr($url, 0, 4), ['http', 'ftp:'], true)) {
236 7
                    $url = \Yii::getAlias($this->view->basePath . $url);
237 7
                }
238
239 7
                $result = file_get_contents($url);
240 7
            }
241 7
        }
242
243 7
        return $result;
244
    }
245
}
246