Created
March 20, 2022 08:54
-
-
Save beekalam/ba54425b0071bdae31606d4caf053ff2 to your computer and use it in GitHub Desktop.
laravel minifier middleware
This file contains hidden or 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 | |
| // @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