1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ArjanSchouten\HtmlMinifier\Minifiers\Html; |
4
|
|
|
|
5
|
|
|
use ArjanSchouten\HtmlMinifier\Constants; |
6
|
|
|
use ArjanSchouten\HtmlMinifier\Minifiers\MinifierInterface; |
7
|
|
|
use ArjanSchouten\HtmlMinifier\MinifyContext; |
8
|
|
|
use ArjanSchouten\HtmlMinifier\Options; |
9
|
|
|
use Illuminate\Support\Str; |
10
|
|
|
|
11
|
|
|
class AttributeQuoteMinifier implements MinifierInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Chars which are prohibited from an unquoted attribute. |
15
|
|
|
* |
16
|
|
|
* @var array |
17
|
|
|
*/ |
18
|
|
|
protected $prohibitedChars = [ |
19
|
|
|
'\'', |
20
|
|
|
'"', |
21
|
|
|
"\n", |
22
|
|
|
'=', |
23
|
|
|
'&', |
24
|
|
|
'`', |
25
|
|
|
'>', |
26
|
|
|
'<', |
27
|
|
|
' ', |
28
|
|
|
]; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Execute the minification rule. |
32
|
|
|
* |
33
|
|
|
* @param \ArjanSchouten\HtmlMinifier\MinifyContext $context |
34
|
|
|
* |
35
|
|
|
* @return \ArjanSchouten\HtmlMinifier\MinifyContext |
36
|
|
|
*/ |
37
|
5 |
|
public function process(MinifyContext $context) |
38
|
|
|
{ |
39
|
5 |
|
return $context->setContents(preg_replace_callback( |
40
|
5 |
|
'/ |
41
|
|
|
= # start matching by a equal sign |
42
|
|
|
\s* # its valid to use whitespaces after the equals sign |
43
|
|
|
(["\'])? # match a single or double quote and make it a capturing group for backreferencing |
44
|
|
|
( |
45
|
|
|
(?:(?=\1)|[^\\\\])* # normal part of "unrolling the loop". Match no quote nor escaped char |
46
|
|
|
(?:\\\\\1 # match the escaped quote |
47
|
|
|
(?:(?=\1)|[^\\\\])* # normal part again |
48
|
|
|
)* # special part of "unrolling the loop" |
49
|
|
|
) # use a the "unrolling the loop" technique to be able to skip escaped quotes like ="\"" |
50
|
|
|
\1? # match the same quote symbol as matched before |
51
|
5 |
|
/x', function ($match) { |
52
|
5 |
|
return $this->minifyAttribute($match); |
53
|
5 |
|
}, $context->getContents())); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Minify the attribute quotes if allowed. |
58
|
|
|
* |
59
|
|
|
* @param array $match |
60
|
|
|
* |
61
|
|
|
* @return string |
62
|
|
|
*/ |
63
|
5 |
|
protected function minifyAttribute($match) |
64
|
|
|
{ |
65
|
5 |
|
if (Str::contains($match[2], $this->prohibitedChars)) { |
66
|
2 |
|
return $match[0]; |
67
|
5 |
|
} elseif (preg_match('/'.Constants::PLACEHOLDER_PATTERN.'/is', $match[2])) { |
68
|
1 |
|
return $match[0]; |
69
|
|
|
} |
70
|
|
|
|
71
|
5 |
|
return '='.$match[2]; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Indicates if minification rules depends on command options. |
76
|
|
|
* |
77
|
|
|
* @return string |
78
|
|
|
*/ |
79
|
3 |
|
public function provides() |
80
|
|
|
{ |
81
|
3 |
|
return Options::ATTRIBUTE_QUOTES; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|