Skip to content

Commit

Permalink
Better minify method for HTML and core CSS
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek committed Jan 6, 2021
1 parent 3f8e413 commit 888acc6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
5 changes: 3 additions & 2 deletions src/Admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ public function run(?string $locale, string $path): void
}
if (($assetType = ($path === 'assets/core.js') ? 'js' : null) || ($assetType = ($path === 'assets/core.css') ? 'css' : null)) { // route static assets from template directory
header('Content-Type: ' . Proxy::CONTENT_TYPES[$assetType]);
$assetContent = file_get_contents(__DIR__ . '/../template/assets/core.' . $assetType)
. (($customAssetPath = $this->context->getCustomAssetPath($assetType)) !== null ? "\n\n" . file_get_contents($customAssetPath) : '');
echo '/*' . "\n"
. ' * This file is part of Baraja CMS.' . "\n"
. ' */' . "\n\n"
. file_get_contents(__DIR__ . '/../template/assets/core.' . $assetType)
. (($customAssetPath = $this->context->getCustomAssetPath($assetType)) !== null ? "\n\n" . file_get_contents($customAssetPath) : '');
. ($assetType === 'css' ? Helpers::minifyHtml($assetContent) : $assetContent);
die;
}
if (strncmp($path, 'cms/', 4) !== 0 && $this->context->getUser()->isLoggedIn() === false) { // route login form
Expand Down
12 changes: 8 additions & 4 deletions src/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -288,13 +288,17 @@ public static function escapeHtmlComment(string $s): string

public static function minifyHtml(string $haystack): string
{
return (string) preg_replace_callback(
$return = (string) preg_replace_callback(
'#[ \t\r\n]+|<(/)?(textarea|pre)(?=\W)#i',
static function (array $match) {
return empty($match[2]) ? ' ' : $match[0];
},
fn (array $match): string => empty($match[2]) ? ' ' : $match[0],
$haystack
);
$return = (string) preg_replace('/(\w|;)\s+({|})\s+(\w|\.|#)/', '$1$2$3', $return);
$return = str_replace(';}', '}', $return);
$return = (string) preg_replace('/(\w)\s*:\s+(\w|#|-|.)/', '$1:$2', $return);
$return = (string) preg_replace('/\s*\/\*+[^\*]+\*+\/\s*/', '', $return);

return $return;
}


Expand Down

0 comments on commit 888acc6

Please sign in to comment.