Subversion Repositories oidplus

Rev

Rev 1308 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 1308 Rev 1469
1
<?php
1
<?php
2
 
2
 
3
/**
3
/**
4
 * CSS Minifier.
4
 * CSS Minifier.
5
 *
5
 *
6
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
6
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
7
 *
7
 *
8
 * @author Matthias Mullie <minify@mullie.eu>
8
 * @author Matthias Mullie <minify@mullie.eu>
9
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
9
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
10
 * @license MIT License
10
 * @license MIT License
11
 */
11
 */
12
 
12
 
13
namespace MatthiasMullie\Minify;
13
namespace MatthiasMullie\Minify;
14
 
14
 
15
use MatthiasMullie\Minify\Exceptions\FileImportException;
15
use MatthiasMullie\Minify\Exceptions\FileImportException;
16
use MatthiasMullie\PathConverter\Converter;
16
use MatthiasMullie\PathConverter\Converter;
17
use MatthiasMullie\PathConverter\ConverterInterface;
17
use MatthiasMullie\PathConverter\ConverterInterface;
18
 
18
 
19
/**
19
/**
20
 * CSS minifier.
20
 * CSS minifier.
21
 *
21
 *
22
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
22
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
23
 *
23
 *
24
 * @author Matthias Mullie <minify@mullie.eu>
24
 * @author Matthias Mullie <minify@mullie.eu>
25
 * @author Tijs Verkoyen <minify@verkoyen.eu>
25
 * @author Tijs Verkoyen <minify@verkoyen.eu>
26
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
26
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
27
 * @license MIT License
27
 * @license MIT License
28
 */
28
 */
29
class CSS extends Minify
29
class CSS extends Minify
30
{
30
{
31
    /**
31
    /**
32
     * @var int maximum inport size in kB
32
     * @var int maximum inport size in kB
33
     */
33
     */
34
    protected $maxImportSize = 5;
34
    protected $maxImportSize = 5;
35
 
35
 
36
    /**
36
    /**
37
     * @var string[] valid import extensions
37
     * @var string[] valid import extensions
38
     */
38
     */
39
    protected $importExtensions = array(
39
    protected $importExtensions = array(
40
        'gif' => 'data:image/gif',
40
        'gif' => 'data:image/gif',
41
        'png' => 'data:image/png',
41
        'png' => 'data:image/png',
42
        'jpe' => 'data:image/jpeg',
42
        'jpe' => 'data:image/jpeg',
43
        'jpg' => 'data:image/jpeg',
43
        'jpg' => 'data:image/jpeg',
44
        'jpeg' => 'data:image/jpeg',
44
        'jpeg' => 'data:image/jpeg',
45
        'svg' => 'data:image/svg+xml',
45
        'svg' => 'data:image/svg+xml',
46
        'woff' => 'data:application/x-font-woff',
46
        'woff' => 'data:application/x-font-woff',
47
        'woff2' => 'data:application/x-font-woff2',
47
        'woff2' => 'data:application/x-font-woff2',
48
        'avif' => 'data:image/avif',
48
        'avif' => 'data:image/avif',
49
        'apng' => 'data:image/apng',
49
        'apng' => 'data:image/apng',
50
        'webp' => 'data:image/webp',
50
        'webp' => 'data:image/webp',
51
        'tif' => 'image/tiff',
51
        'tif' => 'image/tiff',
52
        'tiff' => 'image/tiff',
52
        'tiff' => 'image/tiff',
53
        'xbm' => 'image/x-xbitmap',
53
        'xbm' => 'image/x-xbitmap',
54
    );
54
    );
55
 
55
 
56
    /**
56
    /**
57
     * Set the maximum size if files to be imported.
57
     * Set the maximum size if files to be imported.
58
     *
58
     *
59
     * Files larger than this size (in kB) will not be imported into the CSS.
59
     * Files larger than this size (in kB) will not be imported into the CSS.
60
     * Importing files into the CSS as data-uri will save you some connections,
60
     * Importing files into the CSS as data-uri will save you some connections,
61
     * but we should only import relatively small decorative images so that our
61
     * but we should only import relatively small decorative images so that our
62
     * CSS file doesn't get too bulky.
62
     * CSS file doesn't get too bulky.
63
     *
63
     *
64
     * @param int $size Size in kB
64
     * @param int $size Size in kB
65
     */
65
     */
66
    public function setMaxImportSize($size)
66
    public function setMaxImportSize($size)
67
    {
67
    {
68
        $this->maxImportSize = $size;
68
        $this->maxImportSize = $size;
69
    }
69
    }
70
 
70
 
71
    /**
71
    /**
72
     * Set the type of extensions to be imported into the CSS (to save network
72
     * Set the type of extensions to be imported into the CSS (to save network
73
     * connections).
73
     * connections).
74
     * Keys of the array should be the file extensions & respective values
74
     * Keys of the array should be the file extensions & respective values
75
     * should be the data type.
75
     * should be the data type.
76
     *
76
     *
77
     * @param string[] $extensions Array of file extensions
77
     * @param string[] $extensions Array of file extensions
78
     */
78
     */
79
    public function setImportExtensions(array $extensions)
79
    public function setImportExtensions(array $extensions)
80
    {
80
    {
81
        $this->importExtensions = $extensions;
81
        $this->importExtensions = $extensions;
82
    }
82
    }
83
 
83
 
84
    /**
84
    /**
85
     * Move any import statements to the top.
85
     * Move any import statements to the top.
86
     *
86
     *
87
     * @param string $content Nearly finished CSS content
87
     * @param string $content Nearly finished CSS content
88
     *
88
     *
89
     * @return string
89
     * @return string
90
     */
90
     */
91
    protected function moveImportsToTop($content)
91
    protected function moveImportsToTop($content)
92
    {
92
    {
93
        if (preg_match_all('/(;?)(@import (?<url>url\()?(?P<quotes>["\']?).+?(?P=quotes)(?(url)\)));?/', $content, $matches)) {
93
        if (preg_match_all('/(;?)(@import (?<url>url\()?(?P<quotes>["\']?).+?(?P=quotes)(?(url)\)));?/', $content, $matches)) {
94
            // remove from content
94
            // remove from content
95
            foreach ($matches[0] as $import) {
95
            foreach ($matches[0] as $import) {
96
                $content = str_replace($import, '', $content);
96
                $content = str_replace($import, '', $content);
97
            }
97
            }
98
 
98
 
99
            // add to top
99
            // add to top
100
            $content = implode(';', $matches[2]) . ';' . trim($content, ';');
100
            $content = implode(';', $matches[2]) . ';' . trim($content, ';');
101
        }
101
        }
102
 
102
 
103
        return $content;
103
        return $content;
104
    }
104
    }
105
 
105
 
106
    /**
106
    /**
107
     * Combine CSS from import statements.
107
     * Combine CSS from import statements.
108
     *
108
     *
109
     * Import statements will be loaded and their content merged into the original
109
     * \@import's will be loaded and their content merged into the original file,
110
     * file, to save HTTP requests.
110
     * to save HTTP requests.
111
     *
111
     *
112
     * @param string   $source  The file to combine imports for
112
     * @param string   $source  The file to combine imports for
113
     * @param string   $content The CSS content to combine imports for
113
     * @param string   $content The CSS content to combine imports for
114
     * @param string[] $parents Parent paths, for circular reference checks
114
     * @param string[] $parents Parent paths, for circular reference checks
115
     *
115
     *
116
     * @return string
116
     * @return string
117
     *
117
     *
118
     * @throws FileImportException
118
     * @throws FileImportException
119
     */
119
     */
120
    protected function combineImports($source, $content, $parents)
120
    protected function combineImports($source, $content, $parents)
121
    {
121
    {
122
        $importRegexes = array(
122
        $importRegexes = array(
123
            // @import url(xxx)
123
            // @import url(xxx)
124
            '/
124
            '/
125
            # import statement
125
            # import statement
126
            @import
126
            @import
127
 
127
 
128
            # whitespace
128
            # whitespace
129
            \s+
129
            \s+
130
 
130
 
131
                # open url()
131
                # open url()
132
                url\(
132
                url\(
133
 
133
 
134
                    # (optional) open path enclosure
134
                    # (optional) open path enclosure
135
                    (?P<quotes>["\']?)
135
                    (?P<quotes>["\']?)
136
 
136
 
137
                        # fetch path
137
                        # fetch path
138
                        (?P<path>.+?)
138
                        (?P<path>.+?)
139
 
139
 
140
                    # (optional) close path enclosure
140
                    # (optional) close path enclosure
141
                    (?P=quotes)
141
                    (?P=quotes)
142
 
142
 
143
                # close url()
143
                # close url()
144
                \)
144
                \)
145
 
145
 
146
                # (optional) trailing whitespace
146
                # (optional) trailing whitespace
147
                \s*
147
                \s*
148
 
148
 
149
                # (optional) media statement(s)
149
                # (optional) media statement(s)
150
                (?P<media>[^;]*)
150
                (?P<media>[^;]*)
151
 
151
 
152
                # (optional) trailing whitespace
152
                # (optional) trailing whitespace
153
                \s*
153
                \s*
154
 
154
 
155
            # (optional) closing semi-colon
155
            # (optional) closing semi-colon
156
            ;?
156
            ;?
157
 
157
 
158
            /ix',
158
            /ix',
159
 
159
 
160
            // @import 'xxx'
160
            // @import 'xxx'
161
            '/
161
            '/
162
 
162
 
163
            # import statement
163
            # import statement
164
            @import
164
            @import
165
 
165
 
166
            # whitespace
166
            # whitespace
167
            \s+
167
            \s+
168
 
168
 
169
                # open path enclosure
169
                # open path enclosure
170
                (?P<quotes>["\'])
170
                (?P<quotes>["\'])
171
 
171
 
172
                    # fetch path
172
                    # fetch path
173
                    (?P<path>.+?)
173
                    (?P<path>.+?)
174
 
174
 
175
                # close path enclosure
175
                # close path enclosure
176
                (?P=quotes)
176
                (?P=quotes)
177
 
177
 
178
                # (optional) trailing whitespace
178
                # (optional) trailing whitespace
179
                \s*
179
                \s*
180
 
180
 
181
                # (optional) media statement(s)
181
                # (optional) media statement(s)
182
                (?P<media>[^;]*)
182
                (?P<media>[^;]*)
183
 
183
 
184
                # (optional) trailing whitespace
184
                # (optional) trailing whitespace
185
                \s*
185
                \s*
186
 
186
 
187
            # (optional) closing semi-colon
187
            # (optional) closing semi-colon
188
            ;?
188
            ;?
189
 
189
 
190
            /ix',
190
            /ix',
191
        );
191
        );
192
 
192
 
193
        // find all relative imports in css
193
        // find all relative imports in css
194
        $matches = array();
194
        $matches = array();
195
        foreach ($importRegexes as $importRegex) {
195
        foreach ($importRegexes as $importRegex) {
196
            if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
196
            if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
197
                $matches = array_merge($matches, $regexMatches);
197
                $matches = array_merge($matches, $regexMatches);
198
            }
198
            }
199
        }
199
        }
200
 
200
 
201
        $search = array();
201
        $search = array();
202
        $replace = array();
202
        $replace = array();
203
 
203
 
204
        // loop the matches
204
        // loop the matches
205
        foreach ($matches as $match) {
205
        foreach ($matches as $match) {
206
            // get the path for the file that will be imported
206
            // get the path for the file that will be imported
207
            $importPath = dirname($source) . '/' . $match['path'];
207
            $importPath = dirname($source) . '/' . $match['path'];
208
 
208
 
209
            // only replace the import with the content if we can grab the
209
            // only replace the import with the content if we can grab the
210
            // content of the file
210
            // content of the file
211
            if (!$this->canImportByPath($match['path']) || !$this->canImportFile($importPath)) {
211
            if (!$this->canImportByPath($match['path']) || !$this->canImportFile($importPath)) {
212
                continue;
212
                continue;
213
            }
213
            }
214
 
214
 
215
            // check if current file was not imported previously in the same
215
            // check if current file was not imported previously in the same
216
            // import chain.
216
            // import chain.
217
            if (in_array($importPath, $parents)) {
217
            if (in_array($importPath, $parents)) {
218
                throw new FileImportException('Failed to import file "' . $importPath . '": circular reference detected.');
218
                throw new FileImportException('Failed to import file "' . $importPath . '": circular reference detected.');
219
            }
219
            }
220
 
220
 
221
            // grab referenced file & minify it (which may include importing
221
            // grab referenced file & minify it (which may include importing
222
            // yet other @import statements recursively)
222
            // yet other @import statements recursively)
223
            $minifier = new self($importPath);
223
            $minifier = new self($importPath);
224
            $minifier->setMaxImportSize($this->maxImportSize);
224
            $minifier->setMaxImportSize($this->maxImportSize);
225
            $minifier->setImportExtensions($this->importExtensions);
225
            $minifier->setImportExtensions($this->importExtensions);
226
            $importContent = $minifier->execute($source, $parents);
226
            $importContent = $minifier->execute($source, $parents);
227
 
227
 
228
            // check if this is only valid for certain media
228
            // check if this is only valid for certain media
229
            if (!empty($match['media'])) {
229
            if (!empty($match['media'])) {
230
                $importContent = '@media ' . $match['media'] . '{' . $importContent . '}';
230
                $importContent = '@media ' . $match['media'] . '{' . $importContent . '}';
231
            }
231
            }
232
 
232
 
233
            // add to replacement array
233
            // add to replacement array
234
            $search[] = $match[0];
234
            $search[] = $match[0];
235
            $replace[] = $importContent;
235
            $replace[] = $importContent;
236
        }
236
        }
237
 
237
 
238
        // replace the import statements
238
        // replace the import statements
239
        return str_replace($search, $replace, $content);
239
        return str_replace($search, $replace, $content);
240
    }
240
    }
241
 
241
 
242
    /**
242
    /**
243
     * Import files into the CSS, base64-ized.
243
     * Import files into the CSS, base64-ized.
244
     *
244
     *
245
     * @url(image.jpg) images will be loaded and their content merged into the
245
     * @url(image.jpg) images will be loaded and their content merged into the
246
     * original file, to save HTTP requests.
246
     * original file, to save HTTP requests.
247
     *
247
     *
248
     * @param string $source  The file to import files for
248
     * @param string $source  The file to import files for
249
     * @param string $content The CSS content to import files for
249
     * @param string $content The CSS content to import files for
250
     *
250
     *
251
     * @return string
251
     * @return string
252
     */
252
     */
253
    protected function importFiles($source, $content)
253
    protected function importFiles($source, $content)
254
    {
254
    {
255
        $regex = '/url\((["\']?)(.+?)\\1\)/i';
255
        $regex = '/url\((["\']?)(.+?)\\1\)/i';
256
        if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
256
        if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
257
            $search = array();
257
            $search = array();
258
            $replace = array();
258
            $replace = array();
259
 
259
 
260
            // loop the matches
260
            // loop the matches
261
            foreach ($matches as $match) {
261
            foreach ($matches as $match) {
262
                $extension = substr(strrchr($match[2], '.'), 1);
262
                $extension = substr(strrchr($match[2], '.'), 1);
263
                if ($extension && !array_key_exists($extension, $this->importExtensions)) {
263
                if ($extension && !array_key_exists($extension, $this->importExtensions)) {
264
                    continue;
264
                    continue;
265
                }
265
                }
266
 
266
 
267
                // get the path for the file that will be imported
267
                // get the path for the file that will be imported
268
                $path = $match[2];
268
                $path = $match[2];
269
                $path = dirname($source) . '/' . $path;
269
                $path = dirname($source) . '/' . $path;
270
 
270
 
271
                // only replace the import with the content if we're able to get
271
                // only replace the import with the content if we're able to get
272
                // the content of the file, and it's relatively small
272
                // the content of the file, and it's relatively small
273
                if ($this->canImportFile($path) && $this->canImportBySize($path)) {
273
                if ($this->canImportFile($path) && $this->canImportBySize($path)) {
274
                    // grab content && base64-ize
274
                    // grab content && base64-ize
275
                    $importContent = $this->load($path);
275
                    $importContent = $this->load($path);
276
                    $importContent = base64_encode($importContent);
276
                    $importContent = base64_encode($importContent);
277
 
277
 
278
                    // build replacement
278
                    // build replacement
279
                    $search[] = $match[0];
279
                    $search[] = $match[0];
280
                    $replace[] = 'url(' . $this->importExtensions[$extension] . ';base64,' . $importContent . ')';
280
                    $replace[] = 'url(' . $this->importExtensions[$extension] . ';base64,' . $importContent . ')';
281
                }
281
                }
282
            }
282
            }
283
 
283
 
284
            // replace the import statements
284
            // replace the import statements
285
            $content = str_replace($search, $replace, $content);
285
            $content = str_replace($search, $replace, $content);
286
        }
286
        }
287
 
287
 
288
        return $content;
288
        return $content;
289
    }
289
    }
290
 
290
 
291
    /**
291
    /**
292
     * Minify the data.
292
     * Minify the data.
293
     * Perform CSS optimizations.
293
     * Perform CSS optimizations.
294
     *
294
     *
295
     * @param string[optional] $path    Path to write the data to
295
     * @param string[optional] $path    Path to write the data to
296
     * @param string[] $parents Parent paths, for circular reference checks
296
     * @param string[] $parents Parent paths, for circular reference checks
297
     *
297
     *
298
     * @return string The minified data
298
     * @return string The minified data
299
     */
299
     */
300
    public function execute($path = null, $parents = array())
300
    public function execute($path = null, $parents = array())
301
    {
301
    {
302
        $content = '';
302
        $content = '';
303
 
303
 
304
        // loop CSS data (raw data and files)
304
        // loop CSS data (raw data and files)
305
        foreach ($this->data as $source => $css) {
305
        foreach ($this->data as $source => $css) {
306
            /*
306
            /*
307
             * Let's first take out strings & comments, since we can't just
307
             * Let's first take out strings & comments, since we can't just
308
             * remove whitespace anywhere. If whitespace occurs inside a string,
308
             * remove whitespace anywhere. If whitespace occurs inside a string,
309
             * we should leave it alone. E.g.:
309
             * we should leave it alone. E.g.:
310
             * p { content: "a   test" }
310
             * p { content: "a   test" }
311
             */
311
             */
312
            $this->extractStrings();
312
            $this->extractStrings();
313
            $this->stripComments();
313
            $this->stripComments();
314
            $this->extractMath();
314
            $this->extractMath();
315
            $this->extractCustomProperties();
315
            $this->extractCustomProperties();
316
            $css = $this->replace($css);
316
            $css = $this->replace($css);
317
 
317
 
318
            $css = $this->stripWhitespace($css);
318
            $css = $this->stripWhitespace($css);
-
 
319
            $css = $this->convertLegacyColors($css);
-
 
320
            $css = $this->cleanupModernColors($css);
319
            $css = $this->shortenColors($css);
321
            $css = $this->shortenHEXColors($css);
320
            $css = $this->shortenZeroes($css);
322
            $css = $this->shortenZeroes($css);
321
            $css = $this->shortenFontWeights($css);
323
            $css = $this->shortenFontWeights($css);
322
            $css = $this->stripEmptyTags($css);
324
            $css = $this->stripEmptyTags($css);
323
 
325
 
324
            // restore the string we've extracted earlier
326
            // restore the string we've extracted earlier
325
            $css = $this->restoreExtractedData($css);
327
            $css = $this->restoreExtractedData($css);
326
 
328
 
327
            $source = is_int($source) ? '' : $source;
329
            $source = is_int($source) ? '' : $source;
328
            $parents = $source ? array_merge($parents, array($source)) : $parents;
330
            $parents = $source ? array_merge($parents, array($source)) : $parents;
329
            $css = $this->combineImports($source, $css, $parents);
331
            $css = $this->combineImports($source, $css, $parents);
330
            $css = $this->importFiles($source, $css);
332
            $css = $this->importFiles($source, $css);
331
 
333
 
332
            /*
334
            /*
333
             * If we'll save to a new path, we'll have to fix the relative paths
335
             * If we'll save to a new path, we'll have to fix the relative paths
334
             * to be relative no longer to the source file, but to the new path.
336
             * to be relative no longer to the source file, but to the new path.
335
             * If we don't write to a file, fall back to same path so no
337
             * If we don't write to a file, fall back to same path so no
336
             * conversion happens (because we still want it to go through most
338
             * conversion happens (because we still want it to go through most
337
             * of the move code, which also addresses url() & @import syntax...)
339
             * of the move code, which also addresses url() & @import syntax...)
338
             */
340
             */
339
            $converter = $this->getPathConverter($source, $path ?: $source);
341
            $converter = $this->getPathConverter($source, $path ?: $source);
340
            $css = $this->move($converter, $css);
342
            $css = $this->move($converter, $css);
341
 
343
 
342
            // combine css
344
            // combine css
343
            $content .= $css;
345
            $content .= $css;
344
        }
346
        }
345
 
347
 
346
        $content = $this->moveImportsToTop($content);
348
        $content = $this->moveImportsToTop($content);
347
 
349
 
348
        return $content;
350
        return $content;
349
    }
351
    }
350
 
352
 
351
    /**
353
    /**
352
     * Moving a css file should update all relative urls.
354
     * Moving a css file should update all relative urls.
353
     * Relative references (e.g. ../images/image.gif) in a certain css file,
355
     * Relative references (e.g. ../images/image.gif) in a certain css file,
354
     * will have to be updated when a file is being saved at another location
356
     * will have to be updated when a file is being saved at another location
355
     * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
357
     * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
356
     *
358
     *
357
     * @param ConverterInterface $converter Relative path converter
359
     * @param ConverterInterface $converter Relative path converter
358
     * @param string             $content   The CSS content to update relative urls for
360
     * @param string             $content   The CSS content to update relative urls for
359
     *
361
     *
360
     * @return string
362
     * @return string
361
     */
363
     */
362
    protected function move(ConverterInterface $converter, $content)
364
    protected function move(ConverterInterface $converter, $content)
363
    {
365
    {
364
        /*
366
        /*
365
         * Relative path references will usually be enclosed by url(). @import
367
         * Relative path references will usually be enclosed by url(). @import
366
         * is an exception, where url() is not necessary around the path (but is
368
         * is an exception, where url() is not necessary around the path (but is
367
         * allowed).
369
         * allowed).
368
         * This *could* be 1 regular expression, where both regular expressions
370
         * This *could* be 1 regular expression, where both regular expressions
369
         * in this array are on different sides of a |. But we're using named
371
         * in this array are on different sides of a |. But we're using named
370
         * patterns in both regexes, the same name on both regexes. This is only
372
         * patterns in both regexes, the same name on both regexes. This is only
371
         * possible with a (?J) modifier, but that only works after a fairly
373
         * possible with a (?J) modifier, but that only works after a fairly
372
         * recent PCRE version. That's why I'm doing 2 separate regular
374
         * recent PCRE version. That's why I'm doing 2 separate regular
373
         * expressions & combining the matches after executing of both.
375
         * expressions & combining the matches after executing of both.
374
         */
376
         */
375
        $relativeRegexes = array(
377
        $relativeRegexes = array(
376
            // url(xxx)
378
            // url(xxx)
377
            '/
379
            '/
378
            # open url()
380
            # open url()
379
            url\(
381
            url\(
380
 
382
 
381
                \s*
383
                \s*
382
 
384
 
383
                # open path enclosure
385
                # open path enclosure
384
                (?P<quotes>["\'])?
386
                (?P<quotes>["\'])?
385
 
387
 
386
                    # fetch path
388
                    # fetch path
387
                    (?P<path>.+?)
389
                    (?P<path>.+?)
388
 
390
 
389
                # close path enclosure
391
                # close path enclosure
390
                (?(quotes)(?P=quotes))
392
                (?(quotes)(?P=quotes))
391
 
393
 
392
                \s*
394
                \s*
393
 
395
 
394
            # close url()
396
            # close url()
395
            \)
397
            \)
396
 
398
 
397
            /ix',
399
            /ix',
398
 
400
 
399
            // @import "xxx"
401
            // @import "xxx"
400
            '/
402
            '/
401
            # import statement
403
            # import statement
402
            @import
404
            @import
403
 
405
 
404
            # whitespace
406
            # whitespace
405
            \s+
407
            \s+
406
 
408
 
407
                # we don\'t have to check for @import url(), because the
409
                # we don\'t have to check for @import url(), because the
408
                # condition above will already catch these
410
                # condition above will already catch these
409
 
411
 
410
                # open path enclosure
412
                # open path enclosure
411
                (?P<quotes>["\'])
413
                (?P<quotes>["\'])
412
 
414
 
413
                    # fetch path
415
                    # fetch path
414
                    (?P<path>.+?)
416
                    (?P<path>.+?)
415
 
417
 
416
                # close path enclosure
418
                # close path enclosure
417
                (?P=quotes)
419
                (?P=quotes)
418
 
420
 
419
            /ix',
421
            /ix',
420
        );
422
        );
421
 
423
 
422
        // find all relative urls in css
424
        // find all relative urls in css
423
        $matches = array();
425
        $matches = array();
424
        foreach ($relativeRegexes as $relativeRegex) {
426
        foreach ($relativeRegexes as $relativeRegex) {
425
            if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
427
            if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
426
                $matches = array_merge($matches, $regexMatches);
428
                $matches = array_merge($matches, $regexMatches);
427
            }
429
            }
428
        }
430
        }
429
 
431
 
430
        $search = array();
432
        $search = array();
431
        $replace = array();
433
        $replace = array();
432
 
434
 
433
        // loop all urls
435
        // loop all urls
434
        foreach ($matches as $match) {
436
        foreach ($matches as $match) {
435
            // determine if it's a url() or an @import match
437
            // determine if it's a url() or an @import match
436
            $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
438
            $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
437
 
439
 
438
            $url = $match['path'];
440
            $url = $match['path'];
439
            if ($this->canImportByPath($url)) {
441
            if ($this->canImportByPath($url)) {
440
                // attempting to interpret GET-params makes no sense, so let's discard them for awhile
442
                // attempting to interpret GET-params makes no sense, so let's discard them for awhile
441
                $params = strrchr($url, '?');
443
                $params = strrchr($url, '?');
442
                $url = $params ? substr($url, 0, -strlen($params)) : $url;
444
                $url = $params ? substr($url, 0, -strlen($params)) : $url;
443
 
445
 
444
                // fix relative url
446
                // fix relative url
445
                $url = $converter->convert($url);
447
                $url = $converter->convert($url);
446
 
448
 
447
                // now that the path has been converted, re-apply GET-params
449
                // now that the path has been converted, re-apply GET-params
448
                $url .= $params;
450
                $url .= $params;
449
            }
451
            }
450
 
452
 
451
            /*
453
            /*
452
             * Urls with control characters above 0x7e should be quoted.
454
             * Urls with control characters above 0x7e should be quoted.
453
             * According to Mozilla's parser, whitespace is only allowed at the
455
             * According to Mozilla's parser, whitespace is only allowed at the
454
             * end of unquoted urls.
456
             * end of unquoted urls.
455
             * Urls with `)` (as could happen with data: uris) should also be
457
             * Urls with `)` (as could happen with data: uris) should also be
456
             * quoted to avoid being confused for the url() closing parentheses.
458
             * quoted to avoid being confused for the url() closing parentheses.
457
             * And urls with a # have also been reported to cause issues.
459
             * And urls with a # have also been reported to cause issues.
458
             * Urls with quotes inside should also remain escaped.
460
             * Urls with quotes inside should also remain escaped.
459
             *
461
             *
460
             * @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
462
             * @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
461
             * @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
463
             * @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
462
             * @see https://github.com/matthiasmullie/minify/issues/193
464
             * @see https://github.com/matthiasmullie/minify/issues/193
463
             */
465
             */
464
            $url = trim($url);
466
            $url = trim($url);
465
            if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
467
            if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
466
                $url = $match['quotes'] . $url . $match['quotes'];
468
                $url = $match['quotes'] . $url . $match['quotes'];
467
            }
469
            }
468
 
470
 
469
            // build replacement
471
            // build replacement
470
            $search[] = $match[0];
472
            $search[] = $match[0];
471
            if ($type === 'url') {
473
            if ($type === 'url') {
472
                $replace[] = 'url(' . $url . ')';
474
                $replace[] = 'url(' . $url . ')';
473
            } elseif ($type === 'import') {
475
            } elseif ($type === 'import') {
474
                $replace[] = '@import "' . $url . '"';
476
                $replace[] = '@import "' . $url . '"';
475
            }
477
            }
476
        }
478
        }
477
 
479
 
478
        // replace urls
480
        // replace urls
479
        return str_replace($search, $replace, $content);
481
        return str_replace($search, $replace, $content);
480
    }
482
    }
481
 
483
 
482
    /**
484
    /**
483
     * Shorthand hex color codes.
485
     * Shorthand HEX color codes.
484
     * #FF0000 -> #F00.
486
     * #FF0000FF -> #f00 -> red
-
 
487
     * #FF00FF00 -> transparent.
485
     *
488
     *
486
     * @param string $content The CSS content to shorten the hex color codes for
489
     * @param string $content The CSS content to shorten the HEX color codes for
487
     *
490
     *
488
     * @return string
491
     * @return string
489
     */
492
     */
490
    protected function shortenColors($content)
493
    protected function shortenHexColors($content)
491
    {
494
    {
-
 
495
        // shorten repeating patterns within HEX ..
492
        $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?:([0-9a-z])\\4)?(?=[; }])/i', '#$1$2$3$4', $content);
496
        $content = preg_replace('/(?<=[: ])#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3(?:([0-9a-f])\\4)?(?=[; }])/i', '#$1$2$3$4', $content);
493
 
497
 
494
        // remove alpha channel if it's pointless...
498
        // remove alpha channel if it's pointless ..
495
        $content = preg_replace('/(?<=[: ])#([0-9a-z]{6})ff?(?=[; }])/i', '#$1', $content);
499
        $content = preg_replace('/(?<=[: ])#([0-9a-f]{6})ff(?=[; }])/i', '#$1', $content);
496
        $content = preg_replace('/(?<=[: ])#([0-9a-z]{3})f?(?=[; }])/i', '#$1', $content);
500
        $content = preg_replace('/(?<=[: ])#([0-9a-f]{3})f(?=[; }])/i', '#$1', $content);
-
 
501
 
-
 
502
        // replace `transparent` with shortcut ..
-
 
503
        $content = preg_replace('/(?<=[: ])#[0-9a-f]{6}00(?=[; }])/i', '#fff0', $content);
497
 
504
 
498
        $colors = array(
505
        $colors = array(
-
 
506
            // make these more readable
-
 
507
            '#00f' => 'blue',
-
 
508
            '#dc143c' => 'crimson',
-
 
509
            '#0ff' => 'cyan',
-
 
510
            '#8b0000' => 'darkred',
-
 
511
            '#696969' => 'dimgray',
-
 
512
            '#ff69b4' => 'hotpink',
-
 
513
            '#0f0' => 'lime',
-
 
514
            '#fdf5e6' => 'oldlace',
-
 
515
            '#87ceeb' => 'skyblue',
-
 
516
            '#d8bfd8' => 'thistle',
499
            // we can shorten some even more by replacing them with their color name
517
            // we can shorten some even more by replacing them with their color name
500
            '#F0FFFF' => 'azure',
518
            '#f0ffff' => 'azure',
501
            '#F5F5DC' => 'beige',
519
            '#f5f5dc' => 'beige',
-
 
520
            '#ffe4c4' => 'bisque',
502
            '#A52A2A' => 'brown',
521
            '#a52a2a' => 'brown',
503
            '#FF7F50' => 'coral',
522
            '#ff7f50' => 'coral',
504
            '#FFD700' => 'gold',
523
            '#ffd700' => 'gold',
505
            '#808080' => 'gray',
524
            '#808080' => 'gray',
506
            '#008000' => 'green',
525
            '#008000' => 'green',
507
            '#4B0082' => 'indigo',
526
            '#4b0082' => 'indigo',
508
            '#FFFFF0' => 'ivory',
527
            '#fffff0' => 'ivory',
509
            '#F0E68C' => 'khaki',
528
            '#f0e68c' => 'khaki',
510
            '#FAF0E6' => 'linen',
529
            '#faf0e6' => 'linen',
511
            '#800000' => 'maroon',
530
            '#800000' => 'maroon',
512
            '#000080' => 'navy',
531
            '#000080' => 'navy',
513
            '#808000' => 'olive',
532
            '#808000' => 'olive',
-
 
533
            '#ffa500' => 'orange',
-
 
534
            '#da70d6' => 'orchid',
514
            '#CD853F' => 'peru',
535
            '#cd853f' => 'peru',
515
            '#FFC0CB' => 'pink',
536
            '#ffc0cb' => 'pink',
516
            '#DDA0DD' => 'plum',
537
            '#dda0dd' => 'plum',
517
            '#800080' => 'purple',
538
            '#800080' => 'purple',
518
            '#F00' => 'red',
539
            '#f00' => 'red',
519
            '#FA8072' => 'salmon',
540
            '#fa8072' => 'salmon',
520
            '#A0522D' => 'sienna',
541
            '#a0522d' => 'sienna',
521
            '#C0C0C0' => 'silver',
542
            '#c0c0c0' => 'silver',
522
            '#FFFAFA' => 'snow',
543
            '#fffafa' => 'snow',
523
            '#D2B48C' => 'tan',
544
            '#d2b48c' => 'tan',
-
 
545
            '#008080' => 'teal',
524
            '#FF6347' => 'tomato',
546
            '#ff6347' => 'tomato',
525
            '#EE82EE' => 'violet',
547
            '#ee82ee' => 'violet',
526
            '#F5DEB3' => 'wheat',
548
            '#f5deb3' => 'wheat',
527
            // or the other way around
549
            // or the other way around
-
 
550
            'black' => '#000',
-
 
551
            'fuchsia' => '#f0f',
-
 
552
            'magenta' => '#f0f',
528
            'WHITE' => '#fff',
553
            'white' => '#fff',
529
            'BLACK' => '#000',
554
            'yellow' => '#ff0',
-
 
555
            // and also `transparent`
-
 
556
            'transparent' => '#fff0',
530
        );
557
        );
531
 
558
 
532
        return preg_replace_callback(
559
        return preg_replace_callback(
533
            '/(?<=[: ])(' . implode('|', array_keys($colors)) . ')(?=[; }])/i',
560
            '/(?<=[: ])(' . implode('|', array_keys($colors)) . ')(?=[; }])/i',
534
            function ($match) use ($colors) {
561
            function ($match) use ($colors) {
535
                return $colors[strtoupper($match[0])];
562
                return $colors[strtolower($match[0])];
-
 
563
            },
-
 
564
            $content
-
 
565
        );
-
 
566
    }
-
 
567
 
-
 
568
    /**
-
 
569
     * Convert RGB|HSL color codes.
-
 
570
     * rgb(255,0,0,.5) -> rgb(255 0 0 / .5).
-
 
571
     * rgb(255,0,0) -> #f00.
-
 
572
     *
-
 
573
     * @param string $content The CSS content to shorten the RGB color codes for
-
 
574
     *
-
 
575
     * @return string
-
 
576
     */
-
 
577
    protected function convertLegacyColors($content)
-
 
578
    {
-
 
579
        /*
-
 
580
          https://drafts.csswg.org/css-color/#color-syntax-legacy
-
 
581
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb
-
 
582
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hsl
-
 
583
        */
-
 
584
 
-
 
585
        // convert legacy color syntax
-
 
586
        $content = preg_replace('/(rgb|hsl)a?\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^\s\)]+)\)/i', '$1($2 $3 $4 / $5)', $content);
-
 
587
        $content = preg_replace('/(rgb|hsl)a?\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)/i', '$1($2 $3 $4)', $content);
-
 
588
 
-
 
589
        // convert `rgb` to `hex`
-
 
590
        $dec = '([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])'; // [000-255] THX @ https://www.regular-expressions.info/numericranges.html
-
 
591
 
-
 
592
        return preg_replace_callback(
-
 
593
            "/rgb\($dec $dec $dec\)/i",
-
 
594
            function ($match) {
-
 
595
                return sprintf('#%02x%02x%02x', $match[1], $match[2], $match[3]);
536
            },
596
            },
537
            $content
597
            $content
538
        );
598
        );
539
    }
599
    }
-
 
600
 
-
 
601
    /**
-
 
602
     * Cleanup RGB|HSL|HWB|LCH|LAB
-
 
603
     * rgb(255 0 0 / 1) -> rgb(255 0 0).
-
 
604
     * rgb(255 0 0 / 0) -> transparent.
-
 
605
     *
-
 
606
     * @param string $content The CSS content to cleanup HSL|HWB|LCH|LAB
-
 
607
     *
-
 
608
     * @return string
-
 
609
     */
-
 
610
    protected function cleanupModernColors($content)
-
 
611
    {
-
 
612
        /*
-
 
613
          https://drafts.csswg.org/css-color/#color-syntax-modern
-
 
614
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hwb
-
 
615
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lch
-
 
616
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lab
-
 
617
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch
-
 
618
          https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklab
-
 
619
        */
-
 
620
        $tag = '(rgb|hsl|hwb|(?:(?:ok)?(?:lch|lab)))';
-
 
621
 
-
 
622
        // remove alpha channel if it's pointless ..
-
 
623
        $content = preg_replace('/' . $tag . '\(([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+\/\s+1(?:[\.\d]*|00%)?\)/i', '$1($2 $3 $4)', $content);
-
 
624
 
-
 
625
        // replace `transparent` with shortcut ..
-
 
626
        $content = preg_replace('/' . $tag . '\([^\s]+\s+[^\s]+\s+[^\s]+\s+\/\s+0(?:[\.0%]*)?\)/i', '#fff0', $content);
-
 
627
 
-
 
628
        return $content;
-
 
629
    }
540
 
630
 
541
    /**
631
    /**
542
     * Shorten CSS font weights.
632
     * Shorten CSS font weights.
543
     *
633
     *
544
     * @param string $content The CSS content to shorten the font weights for
634
     * @param string $content The CSS content to shorten the font weights for
545
     *
635
     *
546
     * @return string
636
     * @return string
547
     */
637
     */
548
    protected function shortenFontWeights($content)
638
    protected function shortenFontWeights($content)
549
    {
639
    {
550
        $weights = array(
640
        $weights = array(
551
            'normal' => 400,
641
            'normal' => 400,
552
            'bold' => 700,
642
            'bold' => 700,
553
        );
643
        );
554
 
644
 
555
        $callback = function ($match) use ($weights) {
645
        $callback = function ($match) use ($weights) {
556
            return $match[1] . $weights[$match[2]];
646
            return $match[1] . $weights[$match[2]];
557
        };
647
        };
558
 
648
 
559
        return preg_replace_callback('/(font-weight\s*:\s*)(' . implode('|', array_keys($weights)) . ')(?=[;}])/', $callback, $content);
649
        return preg_replace_callback('/(font-weight\s*:\s*)(' . implode('|', array_keys($weights)) . ')(?=[;}])/', $callback, $content);
560
    }
650
    }
561
 
651
 
562
    /**
652
    /**
563
     * Shorthand 0 values to plain 0, instead of e.g. -0em.
653
     * Shorthand 0 values to plain 0, instead of e.g. -0em.
564
     *
654
     *
565
     * @param string $content The CSS content to shorten the zero values for
655
     * @param string $content The CSS content to shorten the zero values for
566
     *
656
     *
567
     * @return string
657
     * @return string
568
     */
658
     */
569
    protected function shortenZeroes($content)
659
    protected function shortenZeroes($content)
570
    {
660
    {
571
        // we don't want to strip units in `calc()` expressions:
661
        // we don't want to strip units in `calc()` expressions:
572
        // `5px - 0px` is valid, but `5px - 0` is not
662
        // `5px - 0px` is valid, but `5px - 0` is not
573
        // `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
663
        // `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
574
        // `10 * 0` is invalid
664
        // `10 * 0` is invalid
575
        // we've extracted calcs earlier, so we don't need to worry about this
665
        // we've extracted calcs earlier, so we don't need to worry about this
576
 
666
 
577
        // reusable bits of code throughout these regexes:
667
        // reusable bits of code throughout these regexes:
578
        // before & after are used to make sure we don't match lose unintended
668
        // before & after are used to make sure we don't match lose unintended
579
        // 0-like values (e.g. in #000, or in http://url/1.0)
669
        // 0-like values (e.g. in #000, or in http://url/1.0)
580
        // units can be stripped from 0 values, or used to recognize non 0
670
        // units can be stripped from 0 values, or used to recognize non 0
581
        // values (where wa may be able to strip a .0 suffix)
671
        // values (where wa may be able to strip a .0 suffix)
582
        $before = '(?<=[:(, ])';
672
        $before = '(?<=[:(, ])';
583
        $after = '(?=[ ,);}])';
673
        $after = '(?=[ ,);}])';
584
        $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
674
        $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
585
 
675
 
586
        // strip units after zeroes (0px -> 0)
676
        // strip units after zeroes (0px -> 0)
587
        // NOTE: it should be safe to remove all units for a 0 value, but in
677
        // NOTE: it should be safe to remove all units for a 0 value, but in
588
        // practice, Webkit (especially Safari) seems to stumble over at least
678
        // practice, Webkit (especially Safari) seems to stumble over at least
589
        // 0%, potentially other units as well. Only stripping 'px' for now.
679
        // 0%, potentially other units as well. Only stripping 'px' for now.
590
        // @see https://github.com/matthiasmullie/minify/issues/60
680
        // @see https://github.com/matthiasmullie/minify/issues/60
591
        $content = preg_replace('/' . $before . '(-?0*(\.0+)?)(?<=0)px' . $after . '/', '\\1', $content);
681
        $content = preg_replace('/' . $before . '(-?0*(\.0+)?)(?<=0)px' . $after . '/', '\\1', $content);
592
 
682
 
593
        // strip 0-digits (.0 -> 0)
683
        // strip 0-digits (.0 -> 0)
594
        $content = preg_replace('/' . $before . '\.0+' . $units . '?' . $after . '/', '0\\1', $content);
684
        $content = preg_replace('/' . $before . '\.0+' . $units . '?' . $after . '/', '0\\1', $content);
595
        // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
685
        // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
596
        $content = preg_replace('/' . $before . '(-?[0-9]+\.[0-9]+)0+' . $units . '?' . $after . '/', '\\1\\2', $content);
686
        $content = preg_replace('/' . $before . '(-?[0-9]+\.[0-9]+)0+' . $units . '?' . $after . '/', '\\1\\2', $content);
597
        // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
687
        // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
598
        $content = preg_replace('/' . $before . '(-?[0-9]+)\.0+' . $units . '?' . $after . '/', '\\1\\2', $content);
688
        $content = preg_replace('/' . $before . '(-?[0-9]+)\.0+' . $units . '?' . $after . '/', '\\1\\2', $content);
599
        // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
689
        // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
600
        $content = preg_replace('/' . $before . '(-?)0+([0-9]*\.[0-9]+)' . $units . '?' . $after . '/', '\\1\\2\\3', $content);
690
        $content = preg_replace('/' . $before . '(-?)0+([0-9]*\.[0-9]+)' . $units . '?' . $after . '/', '\\1\\2\\3', $content);
601
 
691
 
602
        // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
692
        // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
603
        $content = preg_replace('/' . $before . '-?0+' . $units . '?' . $after . '/', '0\\1', $content);
693
        $content = preg_replace('/' . $before . '-?0+' . $units . '?' . $after . '/', '0\\1', $content);
604
 
694
 
605
        // IE doesn't seem to understand a unitless flex-basis value (correct -
695
        // IE doesn't seem to understand a unitless flex-basis value (correct -
606
        // it goes against the spec), so let's add it in again (make it `%`,
696
        // it goes against the spec), so let's add it in again (make it `%`,
607
        // which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
697
        // which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
608
        // @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
698
        // @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
609
        $content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
699
        $content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
610
        $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
700
        $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
611
 
701
 
612
        return $content;
702
        return $content;
613
    }
703
    }
614
 
704
 
615
    /**
705
    /**
616
     * Strip empty tags from source code.
706
     * Strip empty tags from source code.
617
     *
707
     *
618
     * @param string $content
708
     * @param string $content
619
     *
709
     *
620
     * @return string
710
     * @return string
621
     */
711
     */
622
    protected function stripEmptyTags($content)
712
    protected function stripEmptyTags($content)
623
    {
713
    {
624
        $content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
714
        $content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
625
        $content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
715
        $content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
626
 
716
 
627
        return $content;
717
        return $content;
628
    }
718
    }
629
 
719
 
630
    /**
720
    /**
631
     * Strip comments from source code.
721
     * Strip comments from source code.
632
     */
722
     */
633
    protected function stripComments()
723
    protected function stripComments()
634
    {
724
    {
635
        $this->stripMultilineComments();
725
        $this->stripMultilineComments();
636
    }
726
    }
637
 
727
 
638
    /**
728
    /**
639
     * Strip whitespace.
729
     * Strip whitespace.
640
     *
730
     *
641
     * @param string $content The CSS content to strip the whitespace for
731
     * @param string $content The CSS content to strip the whitespace for
642
     *
732
     *
643
     * @return string
733
     * @return string
644
     */
734
     */
645
    protected function stripWhitespace($content)
735
    protected function stripWhitespace($content)
646
    {
736
    {
647
        // remove leading & trailing whitespace
737
        // remove leading & trailing whitespace
648
        $content = preg_replace('/^\s*/m', '', $content);
738
        $content = preg_replace('/^\s*/m', '', $content);
649
        $content = preg_replace('/\s*$/m', '', $content);
739
        $content = preg_replace('/\s*$/m', '', $content);
650
 
740
 
651
        // replace newlines with a single space
741
        // replace newlines with a single space
652
        $content = preg_replace('/\s+/', ' ', $content);
742
        $content = preg_replace('/\s+/', ' ', $content);
653
 
743
 
654
        // remove whitespace around meta characters
744
        // remove whitespace around meta characters
655
        // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
745
        // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
656
        $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
746
        $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
657
        $content = preg_replace('/([\[(:>\+])\s+/', '$1', $content);
747
        $content = preg_replace('/([\[(:>\+])\s+/', '$1', $content);
658
        $content = preg_replace('/\s+([\]\)>\+])/', '$1', $content);
748
        $content = preg_replace('/\s+([\]\)>\+])/', '$1', $content);
659
        $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
749
        $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
660
 
750
 
661
        // whitespace around + and - can only be stripped inside some pseudo-
751
        // whitespace around + and - can only be stripped inside some pseudo-
662
        // classes, like `:nth-child(3+2n)`
752
        // classes, like `:nth-child(3+2n)`
663
        // not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
753
        // not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
664
        // selectors like `div.weird- p`
754
        // selectors like `div.weird- p`
665
        $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
755
        $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
666
        $content = preg_replace('/:(' . implode('|', $pseudos) . ')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
756
        $content = preg_replace('/:(' . implode('|', $pseudos) . ')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
667
 
757
 
668
        // remove semicolon/whitespace followed by closing bracket
758
        // remove semicolon/whitespace followed by closing bracket
669
        $content = str_replace(';}', '}', $content);
759
        $content = str_replace(';}', '}', $content);
670
 
760
 
671
        return trim($content);
761
        return trim($content);
672
    }
762
    }
673
 
763
 
674
    /**
764
    /**
675
     * Replace all occurrences of functions that may contain math, where
765
     * Replace all occurrences of functions that may contain math, where
676
     * whitespace around operators needs to be preserved (e.g. calc, clamp).
766
     * whitespace around operators needs to be preserved (e.g. calc, clamp).
677
     */
767
     */
678
    protected function extractMath()
768
    protected function extractMath()
679
    {
769
    {
680
        $functions = array('calc', 'clamp', 'min', 'max');
770
        $functions = array('calc', 'clamp', 'min', 'max');
681
        $pattern = '/\b(' . implode('|', $functions) . ')(\(.+?)(?=$|;|})/m';
771
        $pattern = '/\b(' . implode('|', $functions) . ')(\(.+?)(?=$|;|})/m';
682
 
772
 
683
        // PHP only supports $this inside anonymous functions since 5.4
773
        // PHP only supports $this inside anonymous functions since 5.4
684
        $minifier = $this;
774
        $minifier = $this;
685
        $callback = function ($match) use ($minifier, $pattern, &$callback) {
775
        $callback = function ($match) use ($minifier, $pattern, &$callback) {
686
            $function = $match[1];
776
            $function = $match[1];
687
            $length = strlen($match[2]);
777
            $length = strlen($match[2]);
688
            $expr = '';
778
            $expr = '';
689
            $opened = 0;
779
            $opened = 0;
690
 
780
 
691
            // the regular expression for extracting math has 1 significant problem:
781
            // the regular expression for extracting math has 1 significant problem:
692
            // it can't determine the correct closing parenthesis...
782
            // it can't determine the correct closing parenthesis...
693
            // instead, it'll match a larger portion of code to where it's certain that
783
            // instead, it'll match a larger portion of code to where it's certain that
694
            // the calc() musts have ended, and we'll figure out which is the correct
784
            // the calc() musts have ended, and we'll figure out which is the correct
695
            // closing parenthesis here, by counting how many have opened
785
            // closing parenthesis here, by counting how many have opened
696
            for ($i = 0; $i < $length; ++$i) {
786
            for ($i = 0; $i < $length; ++$i) {
697
                $char = $match[2][$i];
787
                $char = $match[2][$i];
698
                $expr .= $char;
788
                $expr .= $char;
699
                if ($char === '(') {
789
                if ($char === '(') {
700
                    ++$opened;
790
                    ++$opened;
701
                } elseif ($char === ')' && --$opened === 0) {
791
                } elseif ($char === ')' && --$opened === 0) {
702
                    break;
792
                    break;
703
                }
793
                }
704
            }
794
            }
705
 
795
 
706
            // now that we've figured out where the calc() starts and ends, extract it
796
            // now that we've figured out where the calc() starts and ends, extract it
707
            $count = count($minifier->extracted);
797
            $count = count($minifier->extracted);
708
            $placeholder = 'math(' . $count . ')';
798
            $placeholder = 'math(' . $count . ')';
709
            $minifier->extracted[$placeholder] = $function . '(' . trim(substr($expr, 1, -1)) . ')';
799
            $minifier->extracted[$placeholder] = $function . '(' . trim(substr($expr, 1, -1)) . ')';
710
 
800
 
711
            // and since we've captured more code than required, we may have some leftover
801
            // and since we've captured more code than required, we may have some leftover
712
            // calc() in here too - go recursive on the remaining but of code to go figure
802
            // calc() in here too - go recursive on the remaining but of code to go figure
713
            // that out and extract what is needed
803
            // that out and extract what is needed
714
            $rest = $minifier->str_replace_first($function . $expr, '', $match[0]);
804
            $rest = $minifier->str_replace_first($function . $expr, '', $match[0]);
715
            $rest = preg_replace_callback($pattern, $callback, $rest);
805
            $rest = preg_replace_callback($pattern, $callback, $rest);
716
 
806
 
717
            return $placeholder . $rest;
807
            return $placeholder . $rest;
718
        };
808
        };
719
 
809
 
720
        $this->registerPattern($pattern, $callback);
810
        $this->registerPattern($pattern, $callback);
721
    }
811
    }
722
 
812
 
723
    /**
813
    /**
724
     * Replace custom properties, whose values may be used in scenarios where
814
     * Replace custom properties, whose values may be used in scenarios where
725
     * we wouldn't want them to be minified (e.g. inside calc).
815
     * we wouldn't want them to be minified (e.g. inside calc).
726
     */
816
     */
727
    protected function extractCustomProperties()
817
    protected function extractCustomProperties()
728
    {
818
    {
729
        // PHP only supports $this inside anonymous functions since 5.4
819
        // PHP only supports $this inside anonymous functions since 5.4
730
        $minifier = $this;
820
        $minifier = $this;
731
        $this->registerPattern(
821
        $this->registerPattern(
732
            '/(?<=^|[;}{])\s*(--[^:;{}"\'\s]+)\s*:([^;{}]+)/m',
822
            '/(?<=^|[;}{])\s*(--[^:;{}"\'\s]+)\s*:([^;{}]+)/m',
733
            function ($match) use ($minifier) {
823
            function ($match) use ($minifier) {
734
                $placeholder = '--custom-' . count($minifier->extracted) . ':0';
824
                $placeholder = '--custom-' . count($minifier->extracted) . ':0';
735
                $minifier->extracted[$placeholder] = $match[1] . ':' . trim($match[2]);
825
                $minifier->extracted[$placeholder] = $match[1] . ':' . trim($match[2]);
736
 
826
 
737
                return $placeholder;
827
                return $placeholder;
738
            }
828
            }
739
        );
829
        );
740
    }
830
    }
741
 
831
 
742
    /**
832
    /**
743
     * Check if file is small enough to be imported.
833
     * Check if file is small enough to be imported.
744
     *
834
     *
745
     * @param string $path The path to the file
835
     * @param string $path The path to the file
746
     *
836
     *
747
     * @return bool
837
     * @return bool
748
     */
838
     */
749
    protected function canImportBySize($path)
839
    protected function canImportBySize($path)
750
    {
840
    {
751
        return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
841
        return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
752
    }
842
    }
753
 
843
 
754
    /**
844
    /**
755
     * Check if file a file can be imported, going by the path.
845
     * Check if file a file can be imported, going by the path.
756
     *
846
     *
757
     * @param string $path
847
     * @param string $path
758
     *
848
     *
759
     * @return bool
849
     * @return bool
760
     */
850
     */
761
    protected function canImportByPath($path)
851
    protected function canImportByPath($path)
762
    {
852
    {
763
        return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
853
        return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
764
    }
854
    }
765
 
855
 
766
    /**
856
    /**
767
     * Return a converter to update relative paths to be relative to the new
857
     * Return a converter to update relative paths to be relative to the new
768
     * destination.
858
     * destination.
769
     *
859
     *
770
     * @param string $source
860
     * @param string $source
771
     * @param string $target
861
     * @param string $target
772
     *
862
     *
773
     * @return ConverterInterface
863
     * @return ConverterInterface
774
     */
864
     */
775
    protected function getPathConverter($source, $target)
865
    protected function getPathConverter($source, $target)
776
    {
866
    {
777
        return new Converter($source, $target);
867
        return new Converter($source, $target);
778
    }
868
    }
779
}
869
}
780
 
870