33namespace RenatoMarinho \LaravelPageSpeed \Middleware ;
44
55use Closure ;
6+ use RenatoMarinho \LaravelPageSpeed \Entities \HtmlSpecs ;
67use Symfony \Component \HttpFoundation \StreamedResponse ;
78use Symfony \Component \HttpFoundation \BinaryFileResponse ;
89
@@ -109,10 +110,26 @@ protected function shouldProcessPageSpeed($request, $response)
109110 */
110111 protected function matchAllHtmlTag (array $ tags , string $ buffer ): array
111112 {
112- $ tags = '( ' .implode ('| ' , $ tags ).') ' ;
113+ $ voidTags = array_intersect ($ tags , HtmlSpecs::voidElements ());
114+ $ normalTags = array_diff ($ tags , $ voidTags );
113115
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 ];
116133 }
117134
118135 /**
@@ -127,12 +144,11 @@ protected function matchAllHtmlTag(array $tags, string $buffer): array
127144 */
128145 protected function replaceInsideHtmlTags (array $ tags , string $ regex , string $ replace , string $ buffer ): string
129146 {
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 );
132149
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 );
136152 }
137153
138154 return $ buffer ;
0 commit comments