Completed
Push — master ( 9e304d...60eddc )
by Matthias
02:44 queued 29s
created

src/CSS.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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