Files
laysense.cn/app/Content/Assets.php
T

46 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMXPath;
use RuntimeException;
final class Assets
{
public static function cdn(string $value): string
{
$value = rtrim(trim($value), '/');
if ($value !== '' && (strlen($value) > 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) {
throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.laysense.cn。');
}
if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) {
throw new RuntimeException('CDN 端口无效。');
}
return $value;
}
public static function url(string $path, string $cdn): string
{
return str_starts_with($path, '/assets/') ? $cdn . $path : $path;
}
public static function rewrite(string $html, string $cdn): string
{
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();
}
}