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

CSS::process()   C

Complexity

Conditions 12
Paths 9

Size

Total Lines 53
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 6.3525
c 0
b 0
f 0
cc 12
eloc 42
nc 9
nop 1

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
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
}