Completed
Push — master ( 8137b1...e31cbc )
by Revin
05:54 queued 02:12
created

CSS   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 230
Duplicated Lines 8.26 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 4
dl 19
loc 230
ccs 26
cts 26
cp 1
rs 8.6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
C export() 19 34 7
C process() 0 72 12
A removeCssComments() 0 6 2
B expandImports() 0 20 6
A collectCharsets() 0 6 1
A collectImports() 0 6 1
A collectFonts() 0 6 1
A _collect() 0 15 2
B _getImportContent() 0 22 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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