Test Failed
Pull Request — master (#1)
by
unknown
38:28
created

CSS   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 189
Duplicated Lines 10.05 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 4
dl 19
loc 189
rs 8.6
c 0
b 0
f 0

9 Methods

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