Completed
Push — master ( 33048c...308686 )
by Matthias
02:59
created

CSS   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 650
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 4
dl 0
loc 650
rs 8.2222
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setMaxImportSize() 0 4 1
A setImportExtensions() 0 4 1
A moveImportsToTop() 0 14 3
C combineImports() 0 119 8
C importFiles() 0 37 8
B execute() 0 48 5
D move() 0 101 9
B shortenHex() 0 43 1
A shortenFontWeights() 0 13 1
A shortenZeroes() 0 50 2
A stripEmptyTags() 0 4 1
A stripComments() 0 4 1
B stripWhitespace() 0 26 1
A canImportBySize() 0 4 2
A canImportByPath() 0 4 1
A getPathConverter() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like CSS often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CSS, and based on these observations, apply Extract Interface, too.

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

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

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

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