Files
ltsecurityinc/app/code/Plumrocket/CookieConsent/Block/Html/HeadScripts.php
T

110 lines
3.5 KiB
PHP

<?php
/**
* @package Plumrocket_CookieConsent
* @copyright Copyright (c) 2025 Plumrocket Inc. (https://plumrocket.com)
* @license https://plumrocket.com/license End-user License Agreement
*/
declare(strict_types=1);
namespace Plumrocket\CookieConsent\Block\Html;
use Magento\Framework\Code\Minifier\Adapter\Js\JShrink;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\View\Helper\SecureHtmlRenderer;
/**
* @since 2.0.4
*/
class HeadScripts extends Template
{
public const SCRIPT_TAG_REPLACEMENT = 'prcookie-head-script';
/**
* @var \Magento\Framework\Code\Minifier\Adapter\Js\JShrink
*/
private $jsMinifier;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\Code\Minifier\Adapter\Js\JShrink $jsMinifier
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param array $data
*/
public function __construct(
Context $context,
JShrink $jsMinifier,
ObjectManagerInterface $objectManager,
array $data = []
) {
parent::__construct($context, $data);
$this->jsMinifier = $jsMinifier;
/**
* @TODO Refactor when leave support of Magento 2.3.7 and less
*/
$this->secureHtmlRenderer = class_exists(SecureHtmlRenderer::class)
? $objectManager->get(SecureHtmlRenderer::class)
: null;
}
protected function _toHtml()
{
$html = parent::_toHtml();
preg_match_all('/<script[\s\S]*?\/script>/', $html, $scriptTags);
$scriptTags = array_shift($scriptTags);
foreach ($scriptTags as $scriptTag) {
try {
$modifiedScriptTag = $this->modifyScriptTag($scriptTag);
} catch (\Exception $e) {
continue;
}
$html = str_replace($scriptTag, $modifiedScriptTag, $html);
}
return $html;
}
/**
* Modify script tag to prevent from being moved to footer
*
* @param string $scriptTag
* @return string
* @throws \Exception
*/
private function modifyScriptTag(string $scriptTag): string
{
/**
* @TODO Refactor when leave support of Magento 2.3.7 and less
*/
if (! $this->secureHtmlRenderer) {
preg_match('#<script[\s\S]*?>([^`]*?)<\/script>#', $scriptTag, $matches);
if(isset($matches[1])) {
$originalTagContent = $matches[1];
$minifiedContent = $this->jsMinifier->minify($originalTagContent);
$scriptTag = str_replace($originalTagContent, $minifiedContent, $scriptTag);
}
return str_replace(
['<script', '/script>'],
['<' . self::SCRIPT_TAG_REPLACEMENT, '/'.self::SCRIPT_TAG_REPLACEMENT.'>'],
$scriptTag
);
}
$doc = new \DOMDocument();
$doc->loadHTML($scriptTag);
$scriptNode = $doc->getElementsByTagName('script')->item(0);
$tagAttributes = array_column(iterator_to_array($scriptNode->attributes), 'nodeValue', 'name');
$tagContent = $this->jsMinifier->minify($scriptNode->textContent);
return $this->secureHtmlRenderer->renderTag(self::SCRIPT_TAG_REPLACEMENT, $tagAttributes, $tagContent, false);
}
}