3
3
namespace RenatoMarinho \LaravelPageSpeed \Middleware ;
4
4
5
5
use Closure ;
6
+ use RenatoMarinho \LaravelPageSpeed \Entities \HtmlSpecs ;
6
7
use Symfony \Component \HttpFoundation \StreamedResponse ;
7
8
use Symfony \Component \HttpFoundation \BinaryFileResponse ;
8
9
@@ -109,10 +110,26 @@ protected function shouldProcessPageSpeed($request, $response)
109
110
*/
110
111
protected function matchAllHtmlTag (array $ tags , string $ buffer ): array
111
112
{
112
- $ tags = '( ' .implode ('| ' , $ tags ).') ' ;
113
+ $ voidTags = array_intersect ($ tags , HtmlSpecs::voidElements ());
114
+ $ normalTags = array_diff ($ tags , $ voidTags );
113
115
114
- preg_match_all ("/\<\s* {$ tags }[^>]*\>((.| \n)*?)\<\s*\/\s* {$ tags }\>/ " , $ buffer , $ matches );
115
- return $ matches ;
116
+ return array_merge (
117
+ $ this ->matchTags ($ voidTags , '/\<\s*(%tags)[^>]*\>/ ' , $ buffer ),
118
+ $ this ->matchTags ($ normalTags , '/\<\s*(%tags)[^>]*\>((.|\n)*?)\<\s*\/\s*(%tags)\>/ ' , $ buffer )
119
+ );
120
+ }
121
+
122
+ protected function matchTags (array $ tags , string $ pattern , string $ buffer ): array
123
+ {
124
+ if (empty ($ tags )) {
125
+ return [];
126
+ }
127
+
128
+ $ normalizedPattern = str_replace ('%tags ' , implode ('| ' , $ tags ), $ pattern );
129
+
130
+ preg_match_all ($ normalizedPattern , $ buffer , $ matches );
131
+
132
+ return $ matches [0 ];
116
133
}
117
134
118
135
/**
@@ -127,12 +144,11 @@ protected function matchAllHtmlTag(array $tags, string $buffer): array
127
144
*/
128
145
protected function replaceInsideHtmlTags (array $ tags , string $ regex , string $ replace , string $ buffer ): string
129
146
{
130
- foreach ($ this ->matchAllHtmlTag ($ tags , $ buffer )[ 0 ] as $ tagMatched ) {
131
- preg_match_all ($ regex , $ tagMatched , $ tagContentsMatchedToReplace );
147
+ foreach ($ this ->matchAllHtmlTag ($ tags , $ buffer ) as $ tagMatched ) {
148
+ preg_match_all ($ regex , $ tagMatched , $ contentsMatched );
132
149
133
- foreach ($ tagContentsMatchedToReplace [0 ] as $ tagContentReplace ) {
134
- $ buffer = str_replace ($ tagContentReplace , $ replace , $ buffer );
135
- }
150
+ $ tagAfterReplace = str_replace ($ contentsMatched [0 ], $ replace , $ tagMatched );
151
+ $ buffer = str_replace ($ tagMatched , $ tagAfterReplace , $ buffer );
136
152
}
137
153
138
154
return $ buffer ;
0 commit comments