Completed
Push — master ( 2fd39c...5d8d2a )
by Revin
02:32
created

CSS::process()   C

Complexity

Conditions 9
Paths 5

Size

Total Lines 64
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 64
ccs 42
cts 42
cp 1
rs 6.5449
cc 9
eloc 36
nc 5
nop 1
crap 9

How to fix   Long Method   

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
use yii\helpers\StringHelper;
12
13
/**
14
 * Class CSS
15
 * @package rmrevin\yii\minify\components
16
 */
17
class CSS extends MinifyComponent
18
{
19
20 4
    public function minify()
21
    {
22 4
        $cssFiles = $this->view->cssFiles;
23
24 4
        $this->view->cssFiles = [];
25
26 4
        $toMinify = [];
27
28 4 View Code Duplication
        foreach ($cssFiles as $file => $html) {
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...
29 4
            if ($this->thisFileNeedMinify($file, $html)) {
30 4
                $toMinify[$file] = $html;
31 4
            } else {
32
                if (!empty($toMinify)) {
33
                    $this->process($toMinify);
34
35
                    $toMinify = [];
36
                }
37
38
                $this->view->cssFiles[$file] = $html;
39
            }
40 4
        }
41
42 4
        if (!empty($toMinify)) {
43 4
            $this->process($toMinify);
44 4
        }
45
46 4
        unset($toMinify);
47 4
    }
48
49
    /**
50
     * @param array $files
51
     */
52 4
    protected function process(array $files)
53
    {
54 4
        $resultFile = $this->view->minify_path . '/' . $this->_getSummaryFilesHash($files) . '.css';
55
56 4
        if (!file_exists($resultFile)) {
57 4
            $css = '';
58
59 4
            foreach ($files as $file => $html) {
60 4
                $path = dirname($file);
61 4
                $file = $this->getAbsoluteFilePath($file);
62
63 4
                $content = file_get_contents($file);
64
65 4
                $result = [];
66
67 4
                preg_match_all('|url\(([^)]+)\)|is', $content, $m);
68 4
                if (!empty($m[0])) {
69 4
                    foreach ($m[0] as $k => $v) {
70 4
                        if (in_array(strpos($m[1][$k], 'data:'), [0, 1], true)) {
71 4
                            continue;
72
                        }
73
74 4
                        $url = str_replace(['\'', '"'], '', $m[1][$k]);
75
76 4
                        if ($this->isUrl($url)) {
77 4
                            $result[$m[1][$k]] = $url;
78 4
                        } else {
79 4
                            $result[$m[1][$k]] = $path . '/' . $url;
80
                        }
81 4
                    }
82
83 4
                    $content = strtr($content, $result);
84 4
                }
85
86 4
                $css .= $content;
87 4
            }
88
89 4
            $this->expandImports($css);
90
91 4
            $this->removeCssComments($css);
92
93 4
            $css = (new \CSSmin())
94 4
                ->run($css, $this->view->css_linebreak_pos);
95
96 4
            if (false !== $this->view->force_charset) {
97 2
                $charsets = '@charset "' . (string)$this->view->force_charset . '";' . "\n";
98 2
            } else {
99 2
                $charsets = $this->collectCharsets($css);
100
            }
101
102 4
            $imports = $this->collectImports($css);
103 4
            $fonts = $this->collectFonts($css);
104
105 4
            file_put_contents($resultFile, $charsets . $imports . $fonts . $css);
106
107 4
            if (false !== $this->view->file_mode) {
108 4
                @chmod($resultFile, $this->view->file_mode);
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...
109 4
            }
110 4
        }
111
112 4
        $file = sprintf('%s%s', \Yii::getAlias($this->view->web_path), str_replace(\Yii::getAlias($this->view->base_path), '', $resultFile));
113
114 4
        $this->view->cssFiles[$file] = Html::cssFile($file);
115 4
    }
116
117
    /**
118
     * @param string $code
119
     */
120 4
    protected function removeCssComments(&$code)
121
    {
122 4
        if (true === $this->view->removeComments) {
123 4
            $code = preg_replace('#/\*(?:[^*]*(?:\*(?!/))*)*\*/#', '', $code);
124 4
        }
125 4
    }
126
127
    /**
128
     * @param string $code
129
     */
130 4
    protected function expandImports(&$code)
131
    {
132 4
        if (true === $this->view->expand_imports) {
133 2
            preg_match_all('|\@import\s([^;]+);|is', str_replace('&amp;', '&', $code), $m);
134 2
            if (!empty($m[0])) {
135 2
                foreach ($m[0] as $k => $v) {
136 2
                    $import_url = $m[1][$k];
137 2
                    if (!empty($import_url)) {
138 2
                        $import_content = $this->_getImportContent($import_url);
139 2
                        if (!empty($import_content)) {
140 2
                            $code = str_replace($m[0][$k], $import_content, $code);
141 2
                        }
142 2
                    }
143 2
                }
144 2
            }
145 2
        }
146 4
    }
147
148
    /**
149
     * @param string $code
150
     * @return string
151
     */
152 2
    protected function collectCharsets(&$code)
153
    {
154
        return $this->_collect($code, '|\@charset[^;]+|is', function ($string) {
155 2
            return $string . ';';
156 2
        });
157
    }
158
159
    /**
160
     * @param string $code
161
     * @return string
162
     */
163 4
    protected function collectImports(&$code)
164
    {
165
        return $this->_collect($code, '|\@import[^;]+|is', function ($string) {
166 2
            return $string . ';';
167 4
        });
168
    }
169
170
    /**
171
     * @param string $code
172
     * @return string
173
     */
174
    protected function collectFonts(&$code)
175
    {
176 4
        return $this->_collect($code, '|\@font-face\{[^}]+\}|is', function ($string) {
177 2
            return $string;
178 4
        });
179
    }
180
181
    /**
182
     * @param string $code
183
     * @param string $pattern
184
     * @param callable $handler
185
     * @return string
186
     */
187 4
    protected function _collect(&$code, $pattern, $handler)
188
    {
189 4
        $result = '';
190
191 4
        preg_match_all($pattern, $code, $m);
192 4
        foreach ($m[0] as $string) {
193 4
            $string = $handler($string);
194 4
            $code = str_replace($string, '', $code);
195
196 4
            $result .= $string . PHP_EOL;
197 4
        }
198
199 4
        return $result;
200
    }
201
202
    /**
203
     * @param string $url
204
     * @return null|string
205
     */
206 2
    protected function _getImportContent($url)
207
    {
208 2
        $result = null;
209
210 2
        if ('url(' === StringHelper::byteSubstr($url, 0, 4)) {
211 2
            $url = str_replace(['url(\'', 'url("', 'url(', '\')', '")', ')'], '', $url);
212
213 2
            if (StringHelper::byteSubstr($url, 0, 2) === '//') {
214 2
                $url = preg_replace('|^//|', 'http://', $url, 1);
215 2
            }
216
217 2
            if (!empty($url)) {
218 2
                $result = file_get_contents($url);
219 2
            }
220 2
        }
221
222 2
        return $result;
223
    }
224
}