Completed
Pull Request — master (#33)
by Dmytro
02:26
created

CSS::_getImportContent()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5

Importance

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