stylehub/lib/inliner.php

69 lines
2.0 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 10:42:36 +01:00
$cssContent = preg_replace_callback('/url\(["\']?(\/.*?|.*?)["\']?\)/i', function($urlMatch) use ($cssDir) {
2024-02-04 10:32:08 +01:00
$url = $urlMatch[1];
2024-02-04 10:42:36 +01:00
$absolutePath = $cssDir . '/' . $url;
$relativePath = ltrim(substr($absolutePath, strlen($_SERVER['DOCUMENT_ROOT'])), '/');
2024-02-04 10:45:44 +01:00
return 'url("' . $relativePath . '")';
2024-02-04 10:32:08 +01:00
}, $cssContent);
2024-02-04 10:45:44 +01:00
// Minify the CSS content
$cssContent = minifyCss($cssContent);
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 11:08:12 +01:00
echo $_SERVER['DOCUMENT_ROOT'] . '/' . $src;
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
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
// Remove whitespace
$css = preg_replace('/\s+/', ' ', $css);
// Remove unnecessary semicolons
$css = str_replace(';}', '}', $css);
// Remove spaces around colons
2024-02-04 10:48:07 +01:00
$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
}