-
Notifications
You must be signed in to change notification settings - Fork 3
/
MinifyCss.php
83 lines (72 loc) · 2.98 KB
/
MinifyCss.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace DzId\LaravelHtmlMinifier\Middleware;
class MinifyCss extends Minifier
{
protected static $allowInsertSemicolon;
protected function apply()
{
static::$minifyCssHasBeenUsed = true;
static::$allowInsertSemicolon = (bool) config("laravel-html-minifier.css_automatic_insert_semicolon", true);
foreach ($this->getByTag("style") as $el)
{
$value = $this->replace($el->nodeValue);
$el->nodeValue = "";
$el->appendChild(static::$dom->createTextNode($value));
}
return static::$dom->saveHtml();
}
protected function insertSemicolon($value)
{
return preg_replace([
// otomatis menambahkan semicolon atau titik koma (;) diakhir kode
// kecuali yang diakhiri dengan braces ({}) ataupun dengan semicolon (;)
'#^[A-Za-z\s\-]+:.+(?<!({|}|;))$#m',
'#^([A-Za-z\s\-]+):(.+)[;]$(\n+|\s+){#m'
],[
'$0;',
'$1:$2$3{'
], $value);
}
protected function replace($value)
{
if (static::$allowInsertSemicolon)
{
$value = $this->insertSemicolon($value);
}
return trim(preg_replace([
// Remove comment(s)
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
// Remove unused white-space(s)
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
// Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
'#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
// Replace `:0 0 0 0` with `:0`
'#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
// Replace `background-position:0` with `background-position:0 0`
'#(background-position):0(?=[;\}])#si',
// Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
'#(?<=[\s:,\-])0+\.(\d+)#s',
// Minify string value
'#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
'#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
// Minify HEX color code
'#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
// Replace `(border|outline):none` with `(border|outline):0`
'#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
// Remove empty selector(s)
'#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s' //
],[
'$1',
'$1$2$3$4$5$6$7',
'$1',
':0',
'$1:0 0',
'.$1',
'$1$3',
'$1$2$4$5',
'$1$2$3',
'$1:0',
'$1$2'
], $value));
}
}