PHP code example of yahyaerturan / minifier

1. Go to this page and download the library: Download yahyaerturan/minifier library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yahyaerturan / minifier example snippets


use YahyaErturan\Minifier\HtmlMinifier;
use YahyaErturan\Minifier\Options;

$min = new HtmlMinifier(new Options()); // safe defaults
$compact = $min->minify($html);

final class Options
{
    public function __construct(
        // HTML
        public bool $collapseHtmlWhitespace = true,
        public bool $removeHtmlComments = true,
        public bool $preserveBangHtmlComments = true,
        public bool $preserveConditionalComments = true,

        // Inline assets
        public bool $minifyInlineCss = true,
        public bool $minifyInlineJs = true,

        // JS
        public bool $removeJsComments = true,
        public bool $preserveImportantJsComments = true, // /*! … */ or @license/@preserve kept verbatim
        public bool $retainScriptSentinel = true,        // keep /* <\/script> */ when removed comments had </script>

        // CSS
        public bool $removeCssComments = true,
        public bool $preserveImportantCssComments = true, // /*! … */

        // JSON scripts
        public bool $minifyJsonScripts = true,

        // Template tokens
        public array $templateDelimiters = [
            ['{{{','}}}'],
            ['{{','}}'],
            ['{%','%}'],
            ['{#','#}'],
            ['[[',']]'],
        ],

        // Ignore directives
        public bool   $enableIgnoreDirectives = true,
        public string $ignoreOpenComment      = 'minify:off',
        public string $ignoreCloseComment     = 'minify:on',
        public string $ignoreNextComment      = 'minify:ignore-next',
        public string $ignoreAttrName         = 'data-minify',
    ) {}
}

class MinifyHtml
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        if (str_contains($response->headers->get('Content-Type', ''), 'text/html')) {
            $min = new \YahyaErturan\Minifier\HtmlMinifier(new \YahyaErturan\Minifier\Options());
            $response->setContent($min->minify($response->getContent()));
        }
        return $response;
    }
}

public function onKernelResponse(ResponseEvent $event): void
{
    $res = $event->getResponse();
    if (str_contains($res->headers->get('Content-Type', ''), 'text/html')) {
        $min = new \YahyaErturan\Minifier\HtmlMinifier(new \YahyaErturan\Minifier\Options());
        $res->setContent($min->minify($res->getContent()));
    }
}