Created
February 25, 2018 12:29
-
-
Save nasrulhazim/740bdf1175c0ad85be1864c27304aa61 to your computer and use it in GitHub Desktop.
Minify HTML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
class MinifyHtml | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$response = $next($request); | |
return $this->html($response); | |
} | |
public function html($response) | |
{ | |
$buffer = $response->getContent(); | |
$replace = [ | |
'/<!--[^\[](.*?)[^\]]-->/s' => '', | |
"/<\?php/" => '<?php ', | |
"/\n([\S])/" => '$1', | |
"/\r/" => '', | |
"/\n/" => '', | |
"/\t/" => '', | |
'/ +/' => ' ', | |
]; | |
if (false !== strpos($buffer, '<pre>')) { | |
$replace = [ | |
'/<!--[^\[](.*?)[^\]]-->/s' => '', | |
"/<\?php/" => '<?php ', | |
"/\r/" => '', | |
"/>\n</" => '><', | |
"/>\s+\n</" => '><', | |
"/>\n\s+</" => '><', | |
]; | |
} | |
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); | |
$response->setContent($buffer); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment