Completed
Push — master ( fdc238...14be91 )
by Matthias
02:40 queued 43s
created

CSS::importFiles()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
cc 6
eloc 17
nc 2
nop 2
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
        if ($extensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
0 ignored issues
show
Bug Best Practice introduced by Matthias Mullie
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...
241
            $search = array();
242
            $replace = array();
243
244
            // loop the matches
245
            foreach ($matches as $match) {
246
                // get the path for the file that will be imported
247
                $path = $match[2];
248
                $path = dirname($source).'/'.$path;
249
                $extension = $match[3];
250
251
                // only replace the import with the content if we're able to get
252
                // the content of the file, and it's relatively small
253
                if ($this->canImportFile($path) && $this->canImportBySize($path)) {
254
                    // grab content && base64-ize
255
                    $importContent = $this->load($path);
256
                    $importContent = base64_encode($importContent);
257
258
                    // build replacement
259
                    $search[] = $match[0];
260
                    $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
261
                }
262
            }
263
264
            // replace the import statements
265
            $content = str_replace($search, $replace, $content);
266
        }
267
268
        return $content;
269
    }
270
271
    /**
272
     * Minify the data.
273
     * Perform CSS optimizations.
274
     *
275
     * @param string[optional] $path    Path to write the data to
276
     * @param string[]         $parents Parent paths, for circular reference checks
277
     *
278
     * @return string The minified data
279
     */
280
    public function execute($path = null, $parents = array())
281
    {
282
        $content = '';
283
284
        // loop css data (raw data and files)
285
        foreach ($this->data as $source => $css) {
286
            /*
287
             * Let's first take out strings & comments, since we can't just remove
288
             * whitespace anywhere. If whitespace occurs inside a string, we should
289
             * leave it alone. E.g.:
290
             * p { content: "a   test" }
291
             */
292
            $this->extractStrings();
293
            $this->stripComments();
294
            $css = $this->replace($css);
295
296
            $css = $this->stripWhitespace($css);
297
            $css = $this->shortenHex($css);
298
            $css = $this->shortenZeroes($css);
299
            $css = $this->shortenFontWeights($css);
300
            $css = $this->stripEmptyTags($css);
301
302
            // restore the string we've extracted earlier
303
            $css = $this->restoreExtractedData($css);
304
305
            $source = is_int($source) ? '' : $source;
306
            $parents = $source ? array_merge($parents, array($source)) : $parents;
307
            $css = $this->combineImports($source, $css, $parents);
308
            $css = $this->importFiles($source, $css);
309
310
            /*
311
             * If we'll save to a new path, we'll have to fix the relative paths
312
             * to be relative no longer to the source file, but to the new path.
313
             * If we don't write to a file, fall back to same path so no
314
             * conversion happens (because we still want it to go through most
315
             * of the move code...)
316
             */
317
            $converter = new Converter($source, $path ?: $source);
318
            $css = $this->move($converter, $css);
319
320
            // combine css
321
            $content .= $css;
322
        }
323
324
        $content = $this->moveImportsToTop($content);
325
326
        return $content;
327
    }
328
329
    /**
330
     * Moving a css file should update all relative urls.
331
     * Relative references (e.g. ../images/image.gif) in a certain css file,
332
     * will have to be updated when a file is being saved at another location
333
     * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
334
     *
335
     * @param Converter $converter Relative path converter
336
     * @param string    $content   The CSS content to update relative urls for
337
     *
338
     * @return string
339
     */
340
    protected function move(Converter $converter, $content)
341
    {
342
        /*
343
         * Relative path references will usually be enclosed by url(). @import
344
         * is an exception, where url() is not necessary around the path (but is
345
         * allowed).
346
         * This *could* be 1 regular expression, where both regular expressions
347
         * in this array are on different sides of a |. But we're using named
348
         * patterns in both regexes, the same name on both regexes. This is only
349
         * possible with a (?J) modifier, but that only works after a fairly
350
         * recent PCRE version. That's why I'm doing 2 separate regular
351
         * expressions & combining the matches after executing of both.
352
         */
353
        $relativeRegexes = array(
354
            // url(xxx)
355
            '/
356
            # open url()
357
            url\(
358
359
                \s*
360
361
                # open path enclosure
362
                (?P<quotes>["\'])?
363
364
                    # fetch path
365
                    (?P<path>.+?)
366
367
                # close path enclosure
368
                (?(quotes)(?P=quotes))
369
370
                \s*
371
372
            # close url()
373
            \)
374
375
            /ix',
376
377
            // @import "xxx"
378
            '/
379
            # import statement
380
            @import
381
382
            # whitespace
383
            \s+
384
385
                # we don\'t have to check for @import url(), because the
386
                # condition above will already catch these
387
388
                # open path enclosure
389
                (?P<quotes>["\'])
390
391
                    # fetch path
392
                    (?P<path>.+?)
393
394
                # close path enclosure
395
                (?P=quotes)
396
397
            /ix',
398
        );
399
400
        // find all relative urls in css
401
        $matches = array();
402
        foreach ($relativeRegexes as $relativeRegex) {
403
            if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
404
                $matches = array_merge($matches, $regexMatches);
405
            }
406
        }
407
408
        $search = array();
409
        $replace = array();
410
411
        // loop all urls
412
        foreach ($matches as $match) {
413
            // determine if it's a url() or an @import match
414
            $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
415
416
            $url = $match['path'];
417
            if ($this->canImportByPath($url)) {
418
                // attempting to interpret GET-params makes no sense, so let's discard them for awhile
419
                $params = strrchr($url, '?');
420
                $url = $params ? substr($url, 0, -strlen($params)) : $url;
421
422
                // fix relative url
423
                $url = $converter->convert($url);
424
425
                // now that the path has been converted, re-apply GET-params
426
                $url .= $params;
427
            }
428
429
            // build replacement
430
            $search[] = $match[0];
431
            if ($type === 'url') {
432
                $replace[] = 'url('.$url.')';
433
            } elseif ($type === 'import') {
434
                $replace[] = '@import "'.$url.'"';
435
            }
436
        }
437
438
        // replace urls
439
        return str_replace($search, $replace, $content);
440
    }
441
442
    /**
443
     * Shorthand hex color codes.
444
     * #FF0000 -> #F00.
445
     *
446
     * @param string $content The CSS content to shorten the hex color codes for
447
     *
448
     * @return string
449
     */
450
    protected function shortenHex($content)
451
    {
452
        $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
453
454
        // we can shorten some even more by replacing them with their color name
455
        $colors = array(
456
            '#F0FFFF' => 'azure',
457
            '#F5F5DC' => 'beige',
458
            '#A52A2A' => 'brown',
459
            '#FF7F50' => 'coral',
460
            '#FFD700' => 'gold',
461
            '#808080' => 'gray',
462
            '#008000' => 'green',
463
            '#4B0082' => 'indigo',
464
            '#FFFFF0' => 'ivory',
465
            '#F0E68C' => 'khaki',
466
            '#FAF0E6' => 'linen',
467
            '#800000' => 'maroon',
468
            '#000080' => 'navy',
469
            '#808000' => 'olive',
470
            '#CD853F' => 'peru',
471
            '#FFC0CB' => 'pink',
472
            '#DDA0DD' => 'plum',
473
            '#800080' => 'purple',
474
            '#F00' => 'red',
475
            '#FA8072' => 'salmon',
476
            '#A0522D' => 'sienna',
477
            '#C0C0C0' => 'silver',
478
            '#FFFAFA' => 'snow',
479
            '#D2B48C' => 'tan',
480
            '#FF6347' => 'tomato',
481
            '#EE82EE' => 'violet',
482
            '#F5DEB3' => 'wheat',
483
        );
484
485
        return preg_replace_callback(
486
            '/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
487
            function ($match) use ($colors) {
488
                return $colors[strtoupper($match[0])];
489
            },
490
            $content
491
        );
492
    }
493
494
    /**
495
     * Shorten CSS font weights.
496
     *
497
     * @param string $content The CSS content to shorten the font weights for
498
     *
499
     * @return string
500
     */
501
    protected function shortenFontWeights($content)
502
    {
503
        $weights = array(
504
            'normal' => 400,
505
            'bold' => 700,
506
        );
507
508
        $callback = function ($match) use ($weights) {
509
            return $match[1].$weights[$match[2]];
510
        };
511
512
        return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
513
    }
514
515
    /**
516
     * Shorthand 0 values to plain 0, instead of e.g. -0em.
517
     *
518
     * @param string $content The CSS content to shorten the zero values for
519
     *
520
     * @return string
521
     */
522
    protected function shortenZeroes($content)
523
    {
524
        // reusable bits of code throughout these regexes:
525
        // before & after are used to make sure we don't match lose unintended
526
        // 0-like values (e.g. in #000, or in http://url/1.0)
527
        // units can be stripped from 0 values, or used to recognize non 0
528
        // values (where wa may be able to strip a .0 suffix)
529
        $before = '(?<=[:(, ])';
530
        $after = '(?=[ ,);}])';
531
        $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
532
533
        // strip units after zeroes (0px -> 0)
534
        // NOTE: it should be safe to remove all units for a 0 value, but in
535
        // practice, Webkit (especially Safari) seems to stumble over at least
536
        // 0%, potentially other units as well. Only stripping 'px' for now.
537
        // @see https://github.com/matthiasmullie/minify/issues/60
538
        $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
539
540
        // strip 0-digits (.0 -> 0)
541
        $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
542
        // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
543
        $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
544
        // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
545
        $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
546
        // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
547
        $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
548
549
        // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
550
        $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
551
552
        // remove zeroes where they make no sense in calc: e.g. calc(100px - 0)
553
        // the 0 doesn't have any effect, and this isn't even valid without unit
554
        // strip all `+ 0` or `- 0` occurrences: calc(10% + 0) -> calc(10%)
555
        // looped because there may be multiple 0s inside 1 group of parentheses
556
        do {
557
            $previous = $content;
558
            $content = preg_replace('/\(([^\(\)]+)\s+[\+\-]\s+0(\s+[^\(\)]+)?\)/', '(\\1\\2)', $content);
559
        } while ($content !== $previous);
560
        // strip all `0 +` occurrences: calc(0 + 10%) -> calc(10%)
561
        $content = preg_replace('/\(\s*0\s+\+\s+([^\(\)]+)\)/', '(\\1)', $content);
562
        // strip all `0 -` occurrences: calc(0 - 10%) -> calc(-10%)
563
        $content = preg_replace('/\(\s*0\s+\-\s+([^\(\)]+)\)/', '(-\\1)', $content);
564
        // I'm not going to attempt to optimize away `x * 0` instances:
565
        // it's dumb enough code already that it likely won't occur, and it's
566
        // too complex to do right (order of operations would have to be
567
        // respected etc)
568
        // what I cared about most here was fixing incorrectly truncated units
569
570
        return $content;
571
    }
572
573
    /**
574
     * Strip comments from source code.
575
     *
576
     * @param string $content
577
     *
578
     * @return string
579
     */
580
    protected function stripEmptyTags($content)
581
    {
582
        return preg_replace('/(^|\}|;)[^\{\};]+\{\s*\}/', '\\1', $content);
583
    }
584
585
    /**
586
     * Strip comments from source code.
587
     */
588
    protected function stripComments()
589
    {
590
        $this->registerPattern('/\/\*.*?\*\//s', '');
591
    }
592
593
    /**
594
     * Strip whitespace.
595
     *
596
     * @param string $content The CSS content to strip the whitespace for
597
     *
598
     * @return string
599
     */
600
    protected function stripWhitespace($content)
601
    {
602
        // remove leading & trailing whitespace
603
        $content = preg_replace('/^\s*/m', '', $content);
604
        $content = preg_replace('/\s*$/m', '', $content);
605
606
        // replace newlines with a single space
607
        $content = preg_replace('/\s+/', ' ', $content);
608
609
        // remove whitespace around meta characters
610
        // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
611
        $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
612
        $content = preg_replace('/([\[(:])\s+/', '$1', $content);
613
        $content = preg_replace('/\s+([\]\)])/', '$1', $content);
614
        $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
615
616
        // whitespace around + and - can only be stripped in selectors, like
617
        // :nth-child(3+2n), not in things like calc(3px + 2px) or shorthands
618
        // like 3px -2px
619
        $content = preg_replace('/\s*([+-])\s*(?=[^}]*{)/', '$1', $content);
620
621
        // remove semicolon/whitespace followed by closing bracket
622
        $content = str_replace(';}', '}', $content);
623
624
        return trim($content);
625
    }
626
627
    /**
628
     * Check if file is small enough to be imported.
629
     *
630
     * @param string $path The path to the file
631
     *
632
     * @return bool
633
     */
634
    protected function canImportBySize($path)
635
    {
636
        return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
637
    }
638
639
    /**
640
     * Check if file a file can be imported, going by the path.
641
     *
642
     * @param string $path
643
     *
644
     * @return bool
645
     */
646
    protected function canImportByPath($path)
647
    {
648
        return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
649
    }
650
}
651