Skip to content

Instantly share code, notes, and snippets.

@beekalam
Created March 20, 2022 08:54
Show Gist options
  • Save beekalam/ba54425b0071bdae31606d4caf053ff2 to your computer and use it in GitHub Desktop.
Save beekalam/ba54425b0071bdae31606d4caf053ff2 to your computer and use it in GitHub Desktop.
laravel minifier middleware
<?php
// @snippet.laravel
class Minifier
{
    /**
    * Handle an incoming request.
    *
    * @param \Illuminate\Http\Request $request
    * @param \Closure                $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        /** @var Response $response */
        $response = $next($request);
        $response->setContent(
            $this->minifyHTML($response->getContent())
        );
        return $response;
    }
    public function minifyHTML($htmlString)
    {
        $replace = [
            '<!--(.*?)-->' => '', //remove comments
            "/<\?php/"    => '<?php ',
            "/\n([\S])/"  => '$1',
            "/\r/"        => '', // remove carriage return
            "/\n/"        => '', // remove new lines
            "/\t/"        => '', // remove tab
            "/\s+/"        => ' ', // remove spaces
        ];
        return preg_replace(
            array_keys($replace),
            array_values($replace),
            $htmlString
        );
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment