Completed
Pull Request — master (#155)
by
unknown
04:03
created

CSS::setMaxImportSize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace MatthiasMullie\Minify;
4
5
use MatthiasMullie\Minify\Exceptions\FileImportException;
6
use MatthiasMullie\PathConverter\Converter;
7
8
/**
9
 * CSS minifier.
10
 *
11
 * Please report bugs on https://github.com/matthiasmullie/minify/issues
12
 *
13
 * @author Matthias Mullie <[email protected]>
14
 * @author Tijs Verkoyen <[email protected]>
15
 * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
16
 * @license MIT License
17
 */
18
class CSS extends Minify
19
{
20
    /**
21
     * @var bool
22
     */
23
    protected $fixRelativePath = true;
24
25
    /**
26
     * @var int
27
     */
28
    protected $maxImportSize = 5;
29
30
    /**
31
     * @var string[]
32
     */
33
    protected $importExtensions = array(
34
        'gif' => 'data:image/gif',
35
        'png' => 'data:image/png',
36
        'jpe' => 'data:image/jpeg',
37
        'jpg' => 'data:image/jpeg',
38
        'jpeg' => 'data:image/jpeg',
39
        'svg' => 'data:image/svg+xml',
40
        'woff' => 'data:application/x-font-woff',
41
        'tif' => 'image/tiff',
42
        'tiff' => 'image/tiff',
43
        'xbm' => 'image/x-xbitmap',
44
    );
45
46
    /**
47
     * Set the condition to fix relative path.
48
     *
49
     * @param bool $value
50
     */
51
    public function setFixRelativePath($value)
52
    {
53
        $this->fixRelativePath = $value;
54
    }
55
56
    /**
57
     * Set the maximum size if files to be imported.
58
     *
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,
61
     * but we should only import relatively small decorative images so that our
62
     * CSS file doesn't get too bulky.
63
     *
64
     * @param int $size Size in kB
65
     */
66
    public function setMaxImportSize($size)
67
    {
68
        $this->maxImportSize = $size;
69
    }
70
71
    /**
72
     * Set the type of extensions to be imported into the CSS (to save network
73
     * connections).
74
     * Keys of the array should be the file extensions & respective values
75
     * should be the data type.
76
     *
77
     * @param string[] $extensions Array of file extensions
78
     */
79
    public function setImportExtensions(array $extensions)
80
    {
81
        $this->importExtensions = $extensions;
82
    }
83
84
    /**
85
     * Move any import statements to the top.
86
     *
87
     * @param string $content Nearly finished CSS content
88
     *
89
     * @return string
90
     */
91
    protected function moveImportsToTop($content)
92
    {
93
        if (preg_match_all('/@import[^;]+;/', $content, $matches)) {
94
            // remove from content
95
            foreach ($matches[0] as $import) {
96
                $content = str_replace($import, '', $content);
97
            }
98
99
            // add to top
100
            $content = implode('', $matches[0]).$content;
101
        }
102
103
        return $content;
104
    }
105
106
    /**
107
     * Combine CSS from import statements.
108
     *
109
     * @import's will be loaded and their content merged into the original file,
110
     * to save HTTP requests.
111
     *
112
     * @param string   $source  The file 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
115
     *
116
     * @return string
117
     *
118
     * @throws FileImportException
119
     */
120
    protected function combineImports($source, $content, $parents)
121
    {
122
        $importRegexes = array(
123
            // @import url(xxx)
124
            '/
125
            # import statement
126
            @import
127
128
            # whitespace
129
            \s+
130
131
                # open url()
132
                url\(
133
134
                    # (optional) open path enclosure
135
                    (?P<quotes>["\']?)
136
137
                        # fetch path
138
                        (?P<path>
139
140
                            # do not fetch data uris or external sources
141
                            (?!(
142
                                ["\']?
143
                                (data|https?):
144
                            ))
145
146
                            .+?
147
                        )
148
149
                    # (optional) close path enclosure
150
                    (?P=quotes)
151
152
                # close url()
153
                \)
154
155
                # (optional) trailing whitespace
156
                \s*
157
158
                # (optional) media statement(s)
159
                (?P<media>[^;]*)
160
161
                # (optional) trailing whitespace
162
                \s*
163
164
            # (optional) closing semi-colon
165
            ;?
166
167
            /ix',
168
169
            // @import 'xxx'
170
            '/
171
172
            # import statement
173
            @import
174
175
            # whitespace
176
            \s+
177
178
                # open path enclosure
179
                (?P<quotes>["\'])
180
181
                    # fetch path
182
                    (?P<path>
183
184
                        # do not fetch data uris or external sources
185
                        (?!(
186
                            ["\']?
187
                            (data|https?):
188
                        ))
189
190
                        .+?
191
                    )
192
193
                # close path enclosure
194
                (?P=quotes)
195
196
                # (optional) trailing whitespace
197
                \s*
198
199
                # (optional) media statement(s)
200
                (?P<media>[^;]*)
201
202
                # (optional) trailing whitespace
203
                \s*
204
205
            # (optional) closing semi-colon
206
            ;?
207
208
            /ix',
209
        );
210
211
        // find all relative imports in css
212
        $matches = array();
213
        foreach ($importRegexes as $importRegex) {
214
            if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
215
                $matches = array_merge($matches, $regexMatches);
216
            }
217
        }
218
219
        $search = array();
220
        $replace = array();
221
222
        // loop the matches
223
        foreach ($matches as $match) {
224
            // get the path for the file that will be imported
225
            $importPath = dirname($source).'/'.$match['path'];
226
227
            // only replace the import with the content if we can grab the
228
            // content of the file
229
            if ($this->canImportFile($importPath)) {
230
                // check if current file was not imported previously in the same
231
                // import chain.
232
                if (in_array($importPath, $parents)) {
233
                    throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
234
                }
235
236
                // grab referenced file & minify it (which may include importing
237
                // yet other @import statements recursively)
238
                $minifier = new static($importPath);
239
                $importContent = $minifier->execute($source, $parents);
240
241
                // check if this is only valid for certain media
242
                if (!empty($match['media'])) {
243
                    $importContent = '@media '.$match['media'].'{'.$importContent.'}';
244
                }
245
246
                // add to replacement array
247
                $search[] = $match[0];
248
                $replace[] = $importContent;
249
            }
250
        }
251
252
        // replace the import statements
253
        $content = str_replace($search, $replace, $content);
254
255
        return $content;
256
    }
257
258
    /**
259
     * Import files into the CSS, base64-ized.
260
     *
261
     * @url(image.jpg) images will be loaded and their content merged into the
262
     * original file, to save HTTP requests.
263
     *
264
     * @param string $source  The file to import files for
265
     * @param string $content The CSS content to import files for
266
     *
267
     * @return string
268
     */
269
    protected function importFiles($source, $content)
270
    {
271
        $extensions = array_keys($this->importExtensions);
272
        $regex = '/url\((["\']?)((?!["\']?data:).*?\.('.implode('|', $extensions).'))\\1\)/i';
273
        if ($extensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extensions of type integer[] 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...
274
            $search = array();
275
            $replace = array();
276
277
            // loop the matches
278
            foreach ($matches as $match) {
279
                // get the path for the file that will be imported
280
                $path = $match[2];
281
                $path = dirname($source).'/'.$path;
282
                $extension = $match[3];
283
284
                // only replace the import with the content if we're able to get
285
                // the content of the file, and it's relatively small
286
                if ($this->canImportFile($path) && $this->canImportBySize($path)) {
287
                    // grab content && base64-ize
288
                    $importContent = $this->load($path);
289
                    $importContent = base64_encode($importContent);
290
291
                    // build replacement
292
                    $search[] = $match[0];
293
                    $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
294
                }
295
            }
296
297
            // replace the import statements
298
            $content = str_replace($search, $replace, $content);
299
        }
300
301
        return $content;
302
    }
303
304
    /**
305
     * Minify the data.
306
     * Perform CSS optimizations.
307
     *
308
     * @param string[optional] $path    Path to write the data to
309
     * @param string[]         $parents Parent paths, for circular reference checks
310
     *
311
     * @return string The minified data
312
     */
313
    public function execute($path = null, $parents = array())
314
    {
315
        $content = '';
316
317
        // loop css data (raw data and files)
318
        foreach ($this->data as $source => $css) {
319
            /*
320
             * Let's first take out strings & comments, since we can't just remove
321
             * whitespace anywhere. If whitespace occurs inside a string, we should
322
             * leave it alone. E.g.:
323
             * p { content: "a   test" }
324
             */
325
            $this->extractStrings();
326
            $this->stripComments();
327
            $css = $this->replace($css);
328
329
            $css = $this->stripWhitespace($css);
330
            $css = $this->shortenHex($css);
331
            $css = $this->shortenZeroes($css);
332
            $css = $this->shortenFontWeights($css);
333
            $css = $this->stripEmptyTags($css);
334
335
            // restore the string we've extracted earlier
336
            $css = $this->restoreExtractedData($css);
337
338
            $source = is_int($source) ? '' : $source;
339
            $parents = $source ? array_merge($parents, array($source)) : $parents;
340
            $css = $this->combineImports($source, $css, $parents);
341
            $css = $this->importFiles($source, $css);
342
343
            /*
344
             * If we'll save to a new path, we'll have to fix the relative paths
345
             * to be relative no longer to the source file, but to the new path.
346
             * If we don't write to a file, fall back to same path so no
347
             * conversion happens (because we still want it to go through most
348
             * of the move code...)
349
             */
350
            $converter = new Converter($source, $path ?: $source);
351
            $css = $this->move($converter, $css);
352
353
            // combine css
354
            $content .= $css;
355
        }
356
357
        $content = $this->moveImportsToTop($content);
358
359
        return $content;
360
    }
361
362
    /**
363
     * Moving a css file should update all relative urls.
364
     * Relative references (e.g. ../images/image.gif) in a certain css file,
365
     * will have to be updated when a file is being saved at another location
366
     * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
367
     *
368
     * @param Converter $converter Relative path converter
369
     * @param string    $content   The CSS content to update relative urls for
370
     *
371
     * @return string
372
     */
373
    protected function move(Converter $converter, $content)
374
    {
375
        /*
376
         * Relative path references will usually be enclosed by url(). @import
377
         * is an exception, where url() is not necessary around the path (but is
378
         * allowed).
379
         * This *could* be 1 regular expression, where both regular expressions
380
         * in this array are on different sides of a |. But we're using named
381
         * patterns in both regexes, the same name on both regexes. This is only
382
         * possible with a (?J) modifier, but that only works after a fairly
383
         * recent PCRE version. That's why I'm doing 2 separate regular
384
         * expressions & combining the matches after executing of both.
385
         */
386
        $relativeRegexes = array(
387
            // url(xxx)
388
            '/
389
            # open url()
390
            url\(
391
392
                \s*
393
394
                # open path enclosure
395
                (?P<quotes>["\'])?
396
397
                    # fetch path
398
                    (?P<path>
399
400
                        # do not fetch data uris or external sources
401
                        (?!(
402
                            \s?
403
                            ["\']?
404
                            (data|https?):
405
                        ))
406
407
                        .+?
408
                    )
409
410
                # close path enclosure
411
                (?(quotes)(?P=quotes))
412
413
                \s*
414
415
            # close url()
416
            \)
417
418
            /ix',
419
420
            // @import "xxx"
421
            '/
422
            # import statement
423
            @import
424
425
            # whitespace
426
            \s+
427
428
                # we don\'t have to check for @import url(), because the
429
                # condition above will already catch these
430
431
                # open path enclosure
432
                (?P<quotes>["\'])
433
434
                    # fetch path
435
                    (?P<path>
436
437
                        # do not fetch data uris or external sources
438
                        (?!(
439
                            ["\']?
440
                            (data|https?):
441
                        ))
442
443
                        .+?
444
                    )
445
446
                # close path enclosure
447
                (?P=quotes)
448
449
            /ix',
450
        );
451
452
        // find all relative urls in css
453
        $matches = array();
454
        foreach ($relativeRegexes as $relativeRegex) {
455
            if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
456
                $matches = array_merge($matches, $regexMatches);
457
            }
458
        }
459
460
        $search = array();
461
        $replace = array();
462
463
        // loop all urls
464
        foreach ($matches as $match) {
465
            // determine if it's a url() or an @import match
466
            $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
467
468
            // attempting to interpret GET-params makes no sense, so let's discard them for awhile
469
            $params = strrchr($match['path'], '?');
470
            $url = $params ? substr($match['path'], 0, -strlen($params)) : $match['path'];
471
472
            // fix relative url
473
            if ($this->fixRelativePath) {
474
                $url = $converter->convert($url);
475
            }
476
477
            // now that the path has been converted, re-apply GET-params
478
            $url .= $params;
479
480
            // build replacement
481
            $search[] = $match[0];
482
            if ($type == 'url') {
483
                $replace[] = 'url('.$url.')';
484
            } elseif ($type == 'import') {
485
                $replace[] = '@import "'.$url.'"';
486
            }
487
        }
488
489
        // replace urls
490
        $content = str_replace($search, $replace, $content);
491
492
        return $content;
493
    }
494
495
    /**
496
     * Shorthand hex color codes.
497
     * #FF0000 -> #F00.
498
     *
499
     * @param string $content The CSS content to shorten the hex color codes for
500
     *
501
     * @return string
502
     */
503
    protected function shortenHex($content)
504
    {
505
        $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
506
507
        // we can shorten some even more by replacing them with their color name
508
        $colors = array(
509
            '#F0FFFF' => 'azure',
510
            '#F5F5DC' => 'beige',
511
            '#A52A2A' => 'brown',
512
            '#FF7F50' => 'coral',
513
            '#FFD700' => 'gold',
514
            '#808080' => 'gray',
515
            '#008000' => 'green',
516
            '#4B0082' => 'indigo',
517
            '#FFFFF0' => 'ivory',
518
            '#F0E68C' => 'khaki',
519
            '#FAF0E6' => 'linen',
520
            '#800000' => 'maroon',
521
            '#000080' => 'navy',
522
            '#808000' => 'olive',
523
            '#CD853F' => 'peru',
524
            '#FFC0CB' => 'pink',
525
            '#DDA0DD' => 'plum',
526
            '#800080' => 'purple',
527
            '#F00' => 'red',
528
            '#FA8072' => 'salmon',
529
            '#A0522D' => 'sienna',
530
            '#C0C0C0' => 'silver',
531
            '#FFFAFA' => 'snow',
532
            '#D2B48C' => 'tan',
533
            '#FF6347' => 'tomato',
534
            '#EE82EE' => 'violet',
535
            '#F5DEB3' => 'wheat',
536
        );
537
538
        return preg_replace_callback(
539
            '/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
540
            function ($match) use ($colors) {
541
                return $colors[strtoupper($match[0])];
542
            },
543
            $content
544
        );
545
    }
546
547
    /**
548
     * Shorten CSS font weights.
549
     *
550
     * @param string $content The CSS content to shorten the font weights for
551
     *
552
     * @return string
553
     */
554
    protected function shortenFontWeights($content)
555
    {
556
        $weights = array(
557
            'normal' => 400,
558
            'bold' => 700,
559
        );
560
561
        $callback = function ($match) use ($weights) {
562
            return $match[1].$weights[$match[2]];
563
        };
564
565
        return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
566
    }
567
568
    /**
569
     * Shorthand 0 values to plain 0, instead of e.g. -0em.
570
     *
571
     * @param string $content The CSS content to shorten the zero values for
572
     *
573
     * @return string
574
     */
575
    protected function shortenZeroes($content)
576
    {
577
        // reusable bits of code throughout these regexes:
578
        // 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)
580
        // 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)
582
        $before = '(?<=[:(, ])';
583
        $after = '(?=[ ,);}])';
584
        $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
585
586
        // strip units after zeroes (0px -> 0)
587
        // 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
589
        // 0%, potentially other units as well. Only stripping 'px' for now.
590
        // @see https://github.com/matthiasmullie/minify/issues/60
591
        $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
592
593
        // strip 0-digits (.0 -> 0)
594
        $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
595
        // 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);
597
        // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
598
        $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
599
        // 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);
601
602
        // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
603
        $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
604
605
        // remove zeroes where they make no sense in calc: e.g. calc(100px - 0)
606
        // the 0 doesn't have any effect, and this isn't even valid without unit
607
        // strip all `+ 0` or `- 0` occurrences: calc(10% + 0) -> calc(10%)
608
        // looped because there may be multiple 0s inside 1 group of parentheses
609
        do {
610
            $previous = $content;
611
            $content = preg_replace('/\(([^\(\)]+)\s+[\+\-]\s+0(\s+[^\(\)]+)?\)/', '(\\1\\2)', $content);
612
        } while ($content !== $previous);
613
        // strip all `0 +` occurrences: calc(0 + 10%) -> calc(10%)
614
        $content = preg_replace('/\(\s*0\s+\+\s+([^\(\)]+)\)/', '(\\1)', $content);
615
        // strip all `0 -` occurrences: calc(0 - 10%) -> calc(-10%)
616
        $content = preg_replace('/\(\s*0\s+\-\s+([^\(\)]+)\)/', '(-\\1)', $content);
617
        // I'm not going to attempt to optimize away `x * 0` instances:
618
        // it's dumb enough code already that it likely won't occur, and it's
619
        // too complex to do right (order of operations would have to be
620
        // respected etc)
621
        // what I cared about most here was fixing incorrectly truncated units
622
623
        return $content;
624
    }
625
626
    /**
627
     * Strip comments from source code.
628
     *
629
     * @param string $content
630
     *
631
     * @return string
632
     */
633
    protected function stripEmptyTags($content)
634
    {
635
        return preg_replace('/(^|\}|;)[^\{\};]+\{\s*\}/', '\\1', $content);
636
    }
637
638
    /**
639
     * Strip comments from source code.
640
     */
641
    protected function stripComments()
642
    {
643
        $this->registerPattern('/\/\*.*?\*\//s', '');
644
    }
645
646
    /**
647
     * Strip whitespace.
648
     *
649
     * @param string $content The CSS content to strip the whitespace for
650
     *
651
     * @return string
652
     */
653
    protected function stripWhitespace($content)
654
    {
655
        // remove leading & trailing whitespace
656
        $content = preg_replace('/^\s*/m', '', $content);
657
        $content = preg_replace('/\s*$/m', '', $content);
658
659
        // replace newlines with a single space
660
        $content = preg_replace('/\s+/', ' ', $content);
661
662
        // remove whitespace around meta characters
663
        // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
664
        $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
665
        $content = preg_replace('/([\[(:])\s+/', '$1', $content);
666
        $content = preg_replace('/\s+([\]\)])/', '$1', $content);
667
        $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
668
669
        // whitespace around + and - can only be stripped in selectors, like
670
        // :nth-child(3+2n), not in things like calc(3px + 2px) or shorthands
671
        // like 3px -2px
672
        $content = preg_replace('/\s*([+-])\s*(?=[^}]*{)/', '$1', $content);
673
674
        // remove semicolon/whitespace followed by closing bracket
675
        $content = str_replace(';}', '}', $content);
676
677
        return trim($content);
678
    }
679
680
    /**
681
     * Check if file is small enough to be imported.
682
     *
683
     * @param string $path The path to the file
684
     *
685
     * @return bool
686
     */
687
    protected function canImportBySize($path)
688
    {
689
        return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
690
    }
691
}
692