Cofem/lib/inliner.php

71 lines
2.1 KiB
PHP
Raw Normal View History

2024-02-04 10:21:56 +01:00
<?php
2024-02-04 10:37:06 +01:00
2024-02-04 10:21:56 +01:00
function inlineLocalStylesFromHref($inputString) {
2024-02-04 10:37:06 +01:00
$pattern = '/<link[^>]*?\srel=["\']?stylesheet["\'].*?\shref=["\']?\/(.*?)["\'][^>]*?>/i';
2024-02-04 10:21:56 +01:00
2024-02-04 10:24:52 +01:00
$outputString = preg_replace_callback($pattern, function($match) {
2024-02-04 10:37:06 +01:00
$href = $match[1];
2024-02-04 10:42:36 +01:00
$cssFilePath = $_SERVER['DOCUMENT_ROOT'] . '/' . $href;
$cssContent = file_get_contents($cssFilePath);
$cssDir = dirname($cssFilePath);
2024-02-04 10:21:56 +01:00
2024-02-04 11:11:03 +01:00
$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);
2024-02-04 10:32:08 +01:00
2024-02-04 10:45:44 +01:00
// Minify the CSS content
2024-02-04 11:11:48 +01:00
$cssContent = minifyCss($cssContent);
2024-02-04 10:45:44 +01:00
return "<style>{$cssContent}</style>";
2024-02-04 10:21:56 +01:00
}, $inputString);
return $outputString;
}
function inlineScriptFromSrc($inputString) {
2024-02-04 10:24:52 +01:00
$pattern = '/<script.*?src=["\']\/(.*?)["\'].*?>\s*<\/script>/i';
2024-02-04 10:21:56 +01:00
2024-02-04 10:24:52 +01:00
$outputString = preg_replace_callback($pattern, function($match) {
2024-02-04 10:21:56 +01:00
$src = $match[1];
2024-02-04 10:24:52 +01:00
$jsContent = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $src);
2024-02-04 10:21:56 +01:00
2024-02-04 10:45:44 +01:00
// Minify the JavaScript content
$jsContent = minifyJs($jsContent);
2024-02-04 10:51:34 +01:00
return "<script>{$jsContent}</script>";
2024-02-04 10:21:56 +01:00
}, $inputString);
return $outputString;
2024-02-04 10:45:44 +01:00
}
function minifyCss($css) {
// Remove comments
2024-02-04 11:12:42 +01:00
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
2024-02-04 10:45:44 +01:00
// Remove whitespace
2024-02-04 11:12:54 +01:00
$css = preg_replace('/\s+/', ' ', $css);
2024-02-04 10:45:44 +01:00
2024-02-04 11:13:22 +01:00
// Remove unnecessary semicolons
$css = str_replace(';}', '}', $css);
2024-02-04 10:45:44 +01:00
// Remove spaces around colons
2024-02-04 11:13:22 +01:00
$css = str_replace(': ', ':', $css);
// Remove spaces around commas
$css = str_replace(', ', ',', $css);
2024-02-04 10:45:44 +01:00
return trim($css);
}
function minifyJs($js) {
2024-02-04 10:55:12 +01:00
2024-02-04 10:45:44 +01:00
// Remove newlines and tabs
2024-02-04 11:05:14 +01:00
$js = str_replace("\t", '', $js);
2024-02-04 10:45:44 +01:00
// Remove spaces around operators
2024-02-04 11:07:37 +01:00
$js = preg_replace('~\s*([=+\-*/])\s*~', '$1', $js);
2024-02-04 10:45:44 +01:00
return trim($js);
2024-02-04 10:21:56 +01:00
}