Completed
Pull Request — master (#95)
by Gino
01:51
created

CSS::isNotInImportChain()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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