@@ -55,40 +55,38 @@ public function aroundRenderResult(
5555 ResponseHttp $ response
5656 ) {
5757 $ result = $ proceed ($ response );
58-
5958 if (PHP_SAPI === 'cli ' || $ this ->request ->isXmlHttpRequest () || !$ this ->isEnabled ()) {
6059 return $ result ;
6160 }
6261
6362 $ html = $ response ->getBody ();
63+ $ scripts = [];
64+
65+ $ startTag = '<script ' ;
66+ $ endTag = '</script> ' ;
67+
68+ while (false !== ($ start = mb_stripos ($ html , $ startTag ))) {
69+ $ end = mb_stripos ($ html , $ endTag , $ start );
70+ if (false === $ end ) {
71+ break ;
72+ }
73+
74+ $ len = $ end + mb_strlen ($ endTag ) - $ start ;
75+ $ script = mb_substr ($ html , $ start , $ len );
6476
65- $ patterns = [
66- 'js ' => '#(\s*<!--(\[if[^\n]*>)?\s*(<script.*</script>)+\s*(<!\[endif\])?-->)|(\s*<script.*</script>)#isU ' ,
67- ];
68-
69- $ jsHtml = [];
70-
71- foreach ($ patterns as $ pattern ) {
72- $ matches = [];
73- $ success = preg_match_all ($ pattern , $ html , $ matches );
74- if ($ success ) {
75- foreach ($ matches [0 ] as $ i => $ js ) {
76- if (strpos ($ js , self ::EXCLUDE_FLAG_PATTERN ) !== false ) {
77- unset($ matches [0 ][$ i ]);
78- } else {
79- $ jsHtml [] = $ matches [0 ][$ i ];
80- }
81- }
82-
83- $ html = str_replace ($ matches [0 ], '' , $ html );
77+ if (false !== mb_stripos ($ script , self ::EXCLUDE_FLAG_PATTERN )) {
78+ continue ;
8479 }
80+
81+ $ html = str_replace ($ script , '' , $ html );
82+ $ scripts [] = $ script ;
8583 }
8684
87- $ jsHtml = implode ($ jsHtml );
88- if ($ end = strrpos ($ html , '</body> ' )) {
89- $ html = substr ($ html , 0 , $ end ) . $ jsHtml . substr ($ html , $ end );
85+ $ scripts = implode (PHP_EOL , $ scripts );
86+ if ($ end = mb_stripos ($ html , '</body> ' )) {
87+ $ html = mb_substr ($ html , 0 , $ end ) . $ scripts . substr ($ html , $ end );
9088 } else {
91- $ html .= $ jsHtml ;
89+ $ html .= $ scripts ;
9290 }
9391
9492 $ response ->setBody ($ html );
@@ -112,8 +110,8 @@ private function isEnabled()
112110
113111 if ($ isAmpRequest ) {
114112 /* We know that using objectManager is not a not a good practice,
115- but if Plumrocket_AMP is not installed on your magento instance
116- you'll get error during di:compile */
113+ but if Plumrocket_AMP is not installed on your magento instance
114+ you'll get error during di:compile */
117115 $ objectManager = \Magento \Framework \App \ObjectManager::getInstance ();
118116 $ isAmpRequest = $ objectManager ->get ('\Plumrocket\Amp\Helper\Data ' )
119117 ->isAmpRequest ();
0 commit comments