Preserve HTML during CDN rewrites and refine SHNU benefits layout

This commit is contained in:
2026-11-21 20:53:45 +09:00
parent 474008b06e
commit 173ad30726
2 changed files with 59 additions and 9 deletions
+27 -9
View File
@@ -4,8 +4,6 @@ declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMXPath;
use RuntimeException;
final class Assets
@@ -33,13 +31,33 @@ final class Assets
if ($cdn === '') {
return $html;
}
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML($html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($document);
foreach ($xpath->query('//@src | //@href | //@poster') as $attribute) {
$attribute->value = self::url($attribute->value, $cdn);
}
return $document->saveHTML();
// Match opening tags separately from comments and text-only elements' contents.
$tags = <<<'REGEX'
~<!--.*?(?:-->|\z)|(?<opening><(?:(?<textTag>script|style|textarea|title)|[a-z][\w:-]*)(?=[\s/>])(?:[^<>"']++|"[^"]*"|'[^']*')*+>)(?(textTag)(?<tail>.*?(?:</\k<textTag>\s*>|\z)))~is
REGEX;
$attributes = <<<'REGEX'
~(\s+)([^\s/<>="']+)(?:(\s*=\s*)("[^"]*"|'[^']*'|[^\s<>"'=`]+))?~
REGEX;
return preg_replace_callback($tags, static function (array $tag) use ($attributes, $cdn): string {
if (!isset($tag['opening'])) {
return $tag[0];
}
$opening = preg_replace_callback($attributes, static function (array $attribute) use ($cdn): string {
if (!isset($attribute[4]) || !in_array(strtolower($attribute[2]), ['src', 'href', 'poster'], true)) {
return $attribute[0];
}
$value = $attribute[4];
$quote = str_starts_with($value, '"') || str_starts_with($value, "'") ? $value[0] : '';
$path = $quote === '' ? $value : substr($value, 1, -1);
return $attribute[1] . $attribute[2] . $attribute[3] . $quote . self::url($path, $cdn) . $quote;
}, $tag['opening']) ?? $tag['opening'];
return $opening . ($tag['tail'] ?? '');
}, $html) ?? $html;
}
}