Completed
Pull Request — master (#236)
by
unknown
01:37
created

CSS::moveImportsToTop()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 1
1
<?php
2
/**
3
 * CSS Minifier
4
 *
5
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
6
 *
7
 * @author Matthias Mullie <[email protected]>
8
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
9
 * @license MIT License
10
 */
11
12
namespace MatthiasMullie\Minify;
13
14
use MatthiasMullie\Minify\Exceptions\FileImportException;
15
use MatthiasMullie\PathConverter\ConverterInterface;
16
use MatthiasMullie\PathConverter\Converter;
17
18
/**
19
 * CSS minifier
20
 *
21
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
22
 *
23
 * @package Minify
24
 * @author Matthias Mullie <[email protected]>
25
 * @author Tijs Verkoyen <[email protected]>
26
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
27
 * @license MIT License
28
 */
29
class CSS extends Minify
30
{
31
    /**
32
     * @var int maximum inport size in kB
33
     */
34
    protected $maxImportSize = 5;
35
36
    /**
37
     * @var string[] valid import extensions
38
     */
39
    protected $importExtensions = array(
40
        'gif'  => 'data:image/gif',
41
        'png'  => 'data:image/png',
42
        'jpe'  => 'data:image/jpeg',
43
        'jpg'  => 'data:image/jpeg',
44
        'jpeg' => 'data:image/jpeg',
45
        'svg'  => 'data:image/svg+xml',
46
        'woff' => 'data:application/x-font-woff',
47
        'tif'  => 'image/tiff',
48
        'tiff' => 'image/tiff',
49
        'xbm'  => 'image/x-xbitmap',
50
    );
51
52
    /**
53
     * Set the maximum size if files to be imported.
54
     *
55
     * Files larger than this size (in kB) will not be imported into the CSS.
56
     * Importing files into the CSS as data-uri will save you some connections,
57
     * but we should only import relatively small decorative images so that our
58
     * CSS file doesn't get too bulky.
59
     *
60
     * @param int $size Size in kB
61
     */
62
    public function setMaxImportSize($size)
63
    {
64
        $this->maxImportSize = $size;
65
    }
66
67
    /**
68
     * Set the type of extensions to be imported into the CSS (to save network
69
     * connections).
70
     * Keys of the array should be the file extensions & respective values
71
     * should be the data type.
72
     *
73
     * @param string[] $extensions Array of file extensions
74
     */
75
    public function setImportExtensions(array $extensions)
76
    {
77
        $this->importExtensions = $extensions;
78
    }
79
80
    /**
81
     * Move any import statements to the top.
82
     *
83
     * @param string $content Nearly finished CSS content
84
     *
85
     * @return string
86
     */
87
    protected function moveImportsToTop($content)
88
    {
89
        if (preg_match_all('/(;?)(@import (?<url>url\()?(?P<quotes>["\']?).+?(?P=quotes)(?(url)\)))/', $content, $matches)) {
90
            // remove from content
91
            foreach ($matches[0] as $import) {
92
                $content = str_replace($import, '', $content);
93
            }
94
95
            // add to top
96
            $content = implode(';', $matches[2]) . ';' . trim($content, ';');
97
        }
98
99
        return $content;
100
    }
101
102
    /**
103
     * Combine CSS from import statements.
104
     *
105
     * @import's will be loaded and their content merged into the original file,
106
     * to save HTTP requests.
107
     *
108
     * @param string $source The file to combine imports for
109
     * @param string $content The CSS content to combine imports for
110
     * @param string[] $parents Parent paths, for circular reference checks
111
     *
112
     * @return string
113
     *
114
     * @throws FileImportException
115
     */
116
    protected function combineImports($source, $content, $parents)
117
    {
118
        $importRegexes = array(
119
            // @import url(xxx)
120
            '/
121
            # import statement
122
            @import
123
124
            # whitespace
125
            \s+
126
127
                # open url()
128
                url\(
129
130
                    # (optional) open path enclosure
131
                    (?P<quotes>["\']?)
132
133
                        # fetch path
134
                        (?P<path>.+?)
135
136
                    # (optional) close path enclosure
137
                    (?P=quotes)
138
139
                # close url()
140
                \)
141
142
                # (optional) trailing whitespace
143
                \s*
144
145
                # (optional) media statement(s)
146
                (?P<media>[^;]*)
147
148
                # (optional) trailing whitespace
149
                \s*
150
151
            # (optional) closing semi-colon
152
            ;?
153
154
            /ix',
155
156
            // @import 'xxx'
157
            '/
158
159
            # import statement
160
            @import
161
162
            # whitespace
163
            \s+
164
165
                # open path enclosure
166
                (?P<quotes>["\'])
167
168
                    # fetch path
169
                    (?P<path>.+?)
170
171
                # close path enclosure
172
                (?P=quotes)
173
174
                # (optional) trailing whitespace
175
                \s*
176
177
                # (optional) media statement(s)
178
                (?P<media>[^;]*)
179
180
                # (optional) trailing whitespace
181
                \s*
182
183
            # (optional) closing semi-colon
184
            ;?
185
186
            /ix',
187
        );
188
189
        // find all relative imports in css
190
        $matches = array();
191
        foreach ($importRegexes as $importRegex) {
192
            if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
193
                $matches = array_merge($matches, $regexMatches);
194
            }
195
        }
196
197
        $search = array();
198
        $replace = array();
199
200
        // loop the matches
201
        foreach ($matches as $match) {
202
            // get the path for the file that will be imported
203
            $importPath = dirname($source) . '/' . $match['path'];
204
205
            // only replace the import with the content if we can grab the
206
            // content of the file
207
            if (!$this->canImportByPath($match['path']) || !$this->canImportFile($importPath)) {
208
                continue;
209
            }
210
211
            // check if current file was not imported previously in the same
212
            // import chain.
213
            if (in_array($importPath, $parents)) {
214
                throw new FileImportException('Failed to import file "' . $importPath . '": circular reference detected.');
215
            }
216
217
            // grab referenced file & minify it (which may include importing
218
            // yet other @import statements recursively)
219
            $minifier = new static($importPath);
220
            $importContent = $minifier->execute($source, $parents);
221
222
            // check if this is only valid for certain media
223
            if (!empty($match['media'])) {
224
                $importContent = '@media ' . $match['media'] . '{' . $importContent . '}';
225
            }
226
227
            // add to replacement array
228
            $search[] = $match[0];
229
            $replace[] = $importContent;
230
        }
231
232
        // replace the import statements
233
        return str_replace($search, $replace, $content);
234
    }
235
236
    /**
237
     * Import files into the CSS, base64-ized.
238
     *
239
     * @url(image.jpg) images will be loaded and their content merged into the
240
     * original file, to save HTTP requests.
241
     *
242
     * @param string $source The file to import files for
243
     * @param string $content The CSS content to import files for
244
     *
245
     * @return string
246
     */
247
    protected function importFiles($source, $content)
248
    {
249
        $regex = '/url\((["\']?)(.+?)\\1\)/i';
250
        if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->importExtensions of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
251
            $search = array();
252
            $replace = array();
253
254
            // loop the matches
255
            foreach ($matches as $match) {
256
                $extension = substr(strrchr($match[2], '.'), 1);
257
                if ($extension && !array_key_exists($extension, $this->importExtensions)) {
258
                    continue;
259
                }
260
261
                // get the path for the file that will be imported
262
                $path = $match[2];
263
                $path = dirname($source) . '/' . $path;
264
265
                // only replace the import with the content if we're able to get
266
                // the content of the file, and it's relatively small
267
                if ($this->canImportFile($path) && $this->canImportBySize($path)) {
268
                    // grab content && base64-ize
269
                    $importContent = $this->load($path);
270
                    $importContent = base64_encode($importContent);
271
272
                    // build replacement
273
                    $search[] = $match[0];
274
                    $replace[] = 'url(' . $this->importExtensions[$extension] . ';base64,' . $importContent . ')';
275
                }
276
            }
277
278
            // replace the import statements
279
            $content = str_replace($search, $replace, $content);
280
        }
281
282
        return $content;
283
    }
284
285
    /**
286
     * Minify the data.
287
     * Perform CSS optimizations.
288
     *
289
     * @param string[optional] $path    Path to write the data to
290
     * @param string[] $parents Parent paths, for circular reference checks
291
     *
292
     * @return string The minified data
293
     * @throws FileImportException
294
     */
295
    public function execute($path = null, $parents = array())
296
    {
297
        $content = '';
298
299
        // loop CSS data (raw data and files)
300
        foreach ($this->data as $source => $css) {
301
            /*
302
             * Let's first take out strings & comments, since we can't just
303
             * remove whitespace anywhere. If whitespace occurs inside a string,
304
             * we should leave it alone. E.g.:
305
             * p { content: "a   test" }
306
             */
307
308
            $this->extractStrings();
309
310
            if ($this->options['css-strip-comments'] === true)
311
                $this->stripComments();
312
313
            $css = $this->replace($css);
314
315
            if ($this->options['css-strip-whitespace'] === true)
316
                $css = $this->stripWhitespace($css);
317
318
            if ($this->options['css-shorten-hex'] === true)
319
                $css = $this->shortenHex($css);
320
321
            if ($this->options['css-shorten-zeroes'] === true)
322
                $css = $this->shortenZeroes($css);
323
324
            if ($this->options['css-shorten-font-weights'] === true)
325
                $css = $this->shortenFontWeights($css);
326
327
            if ($this->options['css-strip-empty-tags'] === true)
328
                $css = $this->stripEmptyTags($css);
329
330
            // restore the string we've extracted earlier
331
            $css = $this->restoreExtractedData($css);
332
333
            $source = is_int($source) ? '' : $source;
334
            $parents = $source ? array_merge($parents, array($source)) : $parents;
335
            $css = $this->combineImports($source, $css, $parents);
336
            $css = $this->importFiles($source, $css);
337
338
            /*
339
             * If we'll save to a new path, we'll have to fix the relative paths
340
             * to be relative no longer to the source file, but to the new path.
341
             * If we don't write to a file, fall back to same path so no
342
             * conversion happens (because we still want it to go through most
343
             * of the move code, which also addresses url() & @import syntax...)
344
             */
345
            $converter = $this->getPathConverter($source, $path ?: $source);
346
            $css = $this->move($converter, $css);
347
348
            // combine css
349
            $content .= $css;
350
        }
351
352
        $content = $this->moveImportsToTop($content);
353
354
        /*
355
         * After getting the merged data of all css files
356
         * this method here will remove duplicate css selectors
357
         * for instance, a user might add two css files like default.css & default.css?v=1
358
         * both files contain the same selectors "body {font-family: xxx}"
359
         * this method will deal with those duplicates and remove them from the final content.
360
         */
361
        $content = $this->removeDuplicates($content);
362
363
        return $content;
364
    }
365
366
    /**
367
     * Remove Duplicate CSS Selectors
368
     * for example if there is duplicate body{font-size:13px}
369
     * this method will return one selector
370
     *
371
     * @param $content
372
     * @return string
373
     */
374
    private function removeDuplicates($content)
375
    {
376
377
        // Collect Selectors
378
        preg_match_all('/(?ims)([a-z0-9, \s\.\:#_\-@]+)\{([^\}]*)\}/', $content, $selectors);
379
380
        if (isset($selectors[0]))
381
382
            // return a unique array of selectors and implode it into a string
383
            return implode(null, array_unique($selectors[0]));
384
385
        return $content;
386
    }
387
388
    /**
389
     * Moving a css file should update all relative urls.
390
     * Relative references (e.g. ../images/image.gif) in a certain css file,
391
     * will have to be updated when a file is being saved at another location
392
     * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
393
     *
394
     * @param ConverterInterface $converter Relative path converter
395
     * @param string $content The CSS content to update relative urls for
396
     *
397
     * @return string
398
     */
399
    protected function move(ConverterInterface $converter, $content)
400
    {
401
        /*
402
         * Relative path references will usually be enclosed by url(). @import
403
         * is an exception, where url() is not necessary around the path (but is
404
         * allowed).
405
         * This *could* be 1 regular expression, where both regular expressions
406
         * in this array are on different sides of a |. But we're using named
407
         * patterns in both regexes, the same name on both regexes. This is only
408
         * possible with a (?J) modifier, but that only works after a fairly
409
         * recent PCRE version. That's why I'm doing 2 separate regular
410
         * expressions & combining the matches after executing of both.
411
         */
412
        $relativeRegexes = array(
413
            // url(xxx)
414
            '/
415
            # open url()
416
            url\(
417
418
                \s*
419
420
                # open path enclosure
421
                (?P<quotes>["\'])?
422
423
                    # fetch path
424
                    (?P<path>.+?)
425
426
                # close path enclosure
427
                (?(quotes)(?P=quotes))
428
429
                \s*
430
431
            # close url()
432
            \)
433
434
            /ix',
435
436
            // @import "xxx"
437
            '/
438
            # import statement
439
            @import
440
441
            # whitespace
442
            \s+
443
444
                # we don\'t have to check for @import url(), because the
445
                # condition above will already catch these
446
447
                # open path enclosure
448
                (?P<quotes>["\'])
449
450
                    # fetch path
451
                    (?P<path>.+?)
452
453
                # close path enclosure
454
                (?P=quotes)
455
456
            /ix',
457
        );
458
459
        // find all relative urls in css
460
        $matches = array();
461
        foreach ($relativeRegexes as $relativeRegex) {
462
            if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
463
                $matches = array_merge($matches, $regexMatches);
464
            }
465
        }
466
467
        $search = array();
468
        $replace = array();
469
470
        // loop all urls
471
        foreach ($matches as $match) {
472
            // determine if it's a url() or an @import match
473
            $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
474
475
            $url = $match['path'];
476
            if ($this->canImportByPath($url)) {
477
                // attempting to interpret GET-params makes no sense, so let's discard them for awhile
478
                $params = strrchr($url, '?');
479
                $url = $params ? substr($url, 0, -strlen($params)) : $url;
480
481
                // fix relative url
482
                $url = $converter->convert($url);
483
484
                // now that the path has been converted, re-apply GET-params
485
                $url .= $params;
486
            }
487
488
            /*
489
             * Urls with control characters above 0x7e should be quoted.
490
             * According to Mozilla's parser, whitespace is only allowed at the
491
             * end of unquoted urls.
492
             * Urls with `)` (as could happen with data: uris) should also be
493
             * quoted to avoid being confused for the url() closing parentheses.
494
             * And urls with a # have also been reported to cause issues.
495
             * Urls with quotes inside should also remain escaped.
496
             *
497
             * @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
498
             * @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
499
             * @see https://github.com/matthiasmullie/minify/issues/193
500
             */
501
            $url = trim($url);
502
            if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
503
                $url = $match['quotes'] . $url . $match['quotes'];
504
            }
505
506
            // build replacement
507
            $search[] = $match[0];
508
            if ($type === 'url') {
509
                $replace[] = 'url(' . $url . ')';
510
            } elseif ($type === 'import') {
511
                $replace[] = '@import "' . $url . '"';
512
            }
513
        }
514
515
        // replace urls
516
        return str_replace($search, $replace, $content);
517
    }
518
519
    /**
520
     * Shorthand hex color codes.
521
     * #FF0000 -> #F00.
522
     *
523
     * @param string $content The CSS content to shorten the hex color codes for
524
     *
525
     * @return string
526
     */
527
    protected function shortenHex($content)
528
    {
529
        $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
530
531
        // we can shorten some even more by replacing them with their color name
532
        $colors = array(
533
            '#F0FFFF' => 'azure',
534
            '#F5F5DC' => 'beige',
535
            '#A52A2A' => 'brown',
536
            '#FF7F50' => 'coral',
537
            '#FFD700' => 'gold',
538
            '#808080' => 'gray',
539
            '#008000' => 'green',
540
            '#4B0082' => 'indigo',
541
            '#FFFFF0' => 'ivory',
542
            '#F0E68C' => 'khaki',
543
            '#FAF0E6' => 'linen',
544
            '#800000' => 'maroon',
545
            '#000080' => 'navy',
546
            '#808000' => 'olive',
547
            '#CD853F' => 'peru',
548
            '#FFC0CB' => 'pink',
549
            '#DDA0DD' => 'plum',
550
            '#800080' => 'purple',
551
            '#F00'    => 'red',
552
            '#FA8072' => 'salmon',
553
            '#A0522D' => 'sienna',
554
            '#C0C0C0' => 'silver',
555
            '#FFFAFA' => 'snow',
556
            '#D2B48C' => 'tan',
557
            '#FF6347' => 'tomato',
558
            '#EE82EE' => 'violet',
559
            '#F5DEB3' => 'wheat',
560
        );
561
562
        return preg_replace_callback(
563
            '/(?<=[: ])(' . implode(array_keys($colors), '|') . ')(?=[; }])/i',
564
            function ($match) use ($colors) {
565
                return $colors[strtoupper($match[0])];
566
            },
567
            $content
568
        );
569
    }
570
571
    /**
572
     * Shorten CSS font weights.
573
     *
574
     * @param string $content The CSS content to shorten the font weights for
575
     *
576
     * @return string
577
     */
578
    protected function shortenFontWeights($content)
579
    {
580
        $weights = array(
581
            'normal' => 400,
582
            'bold'   => 700,
583
        );
584
585
        $callback = function ($match) use ($weights) {
586
            return $match[1] . $weights[$match[2]];
587
        };
588
589
        return preg_replace_callback('/(font-weight\s*:\s*)(' . implode('|', array_keys($weights)) . ')(?=[;}])/', $callback, $content);
590
    }
591
592
    /**
593
     * Shorthand 0 values to plain 0, instead of e.g. -0em.
594
     *
595
     * @param string $content The CSS content to shorten the zero values for
596
     *
597
     * @return string
598
     */
599
    protected function shortenZeroes($content)
600
    {
601
        // we don't want to strip units in `calc()` expressions:
602
        // `5px - 0px` is valid, but `5px - 0` is not
603
        // `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
604
        // `10 * 0` is invalid
605
        // best to just leave `calc()`s alone, even if they could be optimized
606
        // (which is a whole other undertaking, where units & order of
607
        // operations all need to be considered...)
608
        $calcs = $this->findCalcs($content);
609
        $content = str_replace($calcs, array_keys($calcs), $content);
610
611
        // reusable bits of code throughout these regexes:
612
        // before & after are used to make sure we don't match lose unintended
613
        // 0-like values (e.g. in #000, or in http://url/1.0)
614
        // units can be stripped from 0 values, or used to recognize non 0
615
        // values (where wa may be able to strip a .0 suffix)
616
        $before = '(?<=[:(, ])';
617
        $after = '(?=[ ,);}])';
618
        $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
619
620
        // strip units after zeroes (0px -> 0)
621
        // NOTE: it should be safe to remove all units for a 0 value, but in
622
        // practice, Webkit (especially Safari) seems to stumble over at least
623
        // 0%, potentially other units as well. Only stripping 'px' for now.
624
        // @see https://github.com/matthiasmullie/minify/issues/60
625
        $content = preg_replace('/' . $before . '(-?0*(\.0+)?)(?<=0)px' . $after . '/', '\\1', $content);
626
627
        // strip 0-digits (.0 -> 0)
628
        $content = preg_replace('/' . $before . '\.0+' . $units . '?' . $after . '/', '0\\1', $content);
629
        // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
630
        $content = preg_replace('/' . $before . '(-?[0-9]+\.[0-9]+)0+' . $units . '?' . $after . '/', '\\1\\2', $content);
631
        // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
632
        $content = preg_replace('/' . $before . '(-?[0-9]+)\.0+' . $units . '?' . $after . '/', '\\1\\2', $content);
633
        // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
634
        $content = preg_replace('/' . $before . '(-?)0+([0-9]*\.[0-9]+)' . $units . '?' . $after . '/', '\\1\\2\\3', $content);
635
636
        // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
637
        $content = preg_replace('/' . $before . '-?0+' . $units . '?' . $after . '/', '0\\1', $content);
638
639
        // IE doesn't seem to understand a unitless flex-basis value (correct -
640
        // it goes against the spec), so let's add it in again (make it `%`,
641
        // which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
642
        // @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
643
        $content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
644
        $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
645
646
        // restore `calc()` expressions
647
        $content = str_replace(array_keys($calcs), $calcs, $content);
648
649
        return $content;
650
    }
651
652
    /**
653
     * Strip empty tags from source code.
654
     *
655
     * @param string $content
656
     *
657
     * @return string
658
     */
659
    protected function stripEmptyTags($content)
660
    {
661
        $content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
662
        $content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
663
664
        return $content;
665
    }
666
667
    /**
668
     * Strip comments from source code.
669
     */
670
    protected function stripComments()
671
    {
672
        $this->registerPattern('/\/\*.*?\*\//s', '');
673
    }
674
675
    /**
676
     * Strip whitespace.
677
     *
678
     * @param string $content The CSS content to strip the whitespace for
679
     *
680
     * @return string
681
     */
682
    protected function stripWhitespace($content)
683
    {
684
        // remove leading & trailing whitespace
685
        $content = preg_replace('/^\s*/m', '', $content);
686
        $content = preg_replace('/\s*$/m', '', $content);
687
688
        // replace newlines with a single space
689
        $content = preg_replace('/\s+/', ' ', $content);
690
691
        // remove whitespace around meta characters
692
        // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
693
        $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
694
        $content = preg_replace('/([\[(:])\s+/', '$1', $content);
695
        $content = preg_replace('/\s+([\]\)])/', '$1', $content);
696
        $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
697
698
        // whitespace around + and - can only be stripped inside some pseudo-
699
        // classes, like `:nth-child(3+2n)`
700
        // not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
701
        // selectors like `div.weird- p`
702
        $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
703
        $content = preg_replace('/:(' . implode('|', $pseudos) . ')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
704
705
        // remove semicolon/whitespace followed by closing bracket
706
        $content = str_replace(';}', '}', $content);
707
708
        return trim($content);
709
    }
710
711
    /**
712
     * Find all `calc()` occurrences.
713
     *
714
     * @param string $content The CSS content to find `calc()`s in.
715
     *
716
     * @return string[]
717
     */
718
    protected function findCalcs($content)
719
    {
720
        $results = array();
721
        preg_match_all('/calc(\(.+?)(?=$|;|calc\()/', $content, $matches, PREG_SET_ORDER);
722
723
        foreach ($matches as $match) {
724
            $length = strlen($match[1]);
725
            $expr = '';
726
            $opened = 0;
727
728
            for ($i = 0; $i < $length; $i++) {
729
                $char = $match[1][$i];
730
                $expr .= $char;
731
                if ($char === '(') {
732
                    $opened++;
733
                } elseif ($char === ')' && --$opened === 0) {
734
                    break;
735
                }
736
            }
737
738
            $results['calc(' . count($results) . ')'] = 'calc' . $expr;
739
        }
740
741
        return $results;
742
    }
743
744
    /**
745
     * Check if file is small enough to be imported.
746
     *
747
     * @param string $path The path to the file
748
     *
749
     * @return bool
750
     */
751
    protected function canImportBySize($path)
752
    {
753
        return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
754
    }
755
756
    /**
757
     * Check if file a file can be imported, going by the path.
758
     *
759
     * @param string $path
760
     *
761
     * @return bool
762
     */
763
    protected function canImportByPath($path)
764
    {
765
        return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
766
    }
767
768
    /**
769
     * Return a converter to update relative paths to be relative to the new
770
     * destination.
771
     *
772
     * @param string $source
773
     * @param string $target
774
     *
775
     * @return ConverterInterface
776
     */
777
    protected function getPathConverter($source, $target)
778
    {
779
        return new Converter($source, $target);
780
    }
781
}
782