Cofem/lib/inliner.php
2024-02-04 10:48:07 +01:00

78 lines
2.4 KiB
PHP

<?php
function inlineLocalStylesFromHref($inputString) {
$pattern = '/<link[^>]*?\srel=["\']?stylesheet["\'].*?\shref=["\']?\/(.*?)["\'][^>]*?>/i';
$outputString = preg_replace_callback($pattern, function($match) {
$href = $match[1];
$cssFilePath = $_SERVER['DOCUMENT_ROOT'] . '/' . $href;
$cssContent = file_get_contents($cssFilePath);
$cssDir = dirname($cssFilePath);
$cssContent = preg_replace_callback('/url\(["\']?(\/.*?|.*?)["\']?\)/i', function($urlMatch) use ($cssDir) {
$url = $urlMatch[1];
$absolutePath = $cssDir . '/' . $url;
$relativePath = ltrim(substr($absolutePath, strlen($_SERVER['DOCUMENT_ROOT'])), '/');
return 'url("' . $relativePath . '")';
}, $cssContent);
// Minify the CSS content
$cssContent = minifyCss($cssContent);
return "<style>{$cssContent}</style>";
}, $inputString);
return $outputString;
}
function inlineScriptFromSrc($inputString) {
$pattern = '/<script.*?src=["\']\/(.*?)["\'].*?>\s*<\/script>/i';
$outputString = preg_replace_callback($pattern, function($match) {
$src = $match[1];
$jsContent = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $src);
// Minify the JavaScript content
$jsContent = minifyJs($jsContent);
$escapedJsContent = htmlspecialchars($jsContent, ENT_QUOTES, 'UTF-8');
return "<script>{$escapedJsContent}</script>";
}, $inputString);
return $outputString;
}
function minifyCss($css) {
// Remove comments
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
// Remove whitespace
$css = preg_replace('/\s+/', ' ', $css);
// Remove unnecessary semicolons
$css = str_replace(';}', '}', $css);
// Remove spaces around colons
$css = str_replace(' ', '', $css);
return trim($css);
}
function minifyJs($js) {
// Remove comments
$js = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $js);
// Remove newlines and tabs
$js = str_replace(array("\r\n", "\r", "\n", "\t"), '', $js);
// Remove unnecessary semicolons
$js = str_replace(';}', '}', $js);
// Remove spaces after function keyword
$js = str_replace('function ', 'function', $js);
// Remove spaces around operators
$js = preg_replace('/\s*([=+\-*/])\s*/', '$1', $js);
return trim($js);
}