Created
January 15, 2016 04:03
-
-
Save gcphost/5c41fc0e3caac052b3b7 to your computer and use it in GitHub Desktop.
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; | |
use Illuminate\Http\Response; | |
class Minify | |
{ | |
public function handle($request, Closure $next) | |
{ | |
$response = $next($request); | |
if ($this->isResponseObject($response) && $this->isHtmlResponse($response)) { | |
$replace = [ | |
'/\>[^\S ]+/s' => '>', | |
'/[^\S ]+\</s' => '<', | |
'/([\t ])+/s' => ' ', | |
'/^([\t ])+/m' => '', | |
'/([\t ])+$/m' => '', | |
'~//[a-zA-Z0-9 ]+$~m' => '', | |
'/[\r\n]+([\t ]?[\r\n]+)+/s' => "\n", | |
'/\>[\r\n\t ]+\</s' => '><', | |
'/}[\r\n\t ]+/s' => '}', | |
'/}[\r\n\t ]+,[\r\n\t ]+/s' => '},', | |
'/\)[\r\n\t ]?{[\r\n\t ]+/s' => '){', | |
'/,[\r\n\t ]?{[\r\n\t ]+/s' => ',{', | |
'/\),[\r\n\t ]+/s' => '),', | |
'~([\r\n\t ])?([a-zA-Z0-9]+)=\"([a-zA-Z0-9_\\-]+)\"([\r\n\t ])?~s' => '$1$2=$3$4', | |
]; | |
$remove = [ | |
'</option>', '</li>', '</dt>', '</dd>', '</tr>', '</th>', '</td>' | |
]; | |
$response->setContent(str_ireplace($remove, '', preg_replace(array_keys($replace), array_values($replace), $response->getContent()))); | |
} | |
return $response; | |
} | |
protected function isResponseObject($response) | |
{ | |
return is_object($response) && $response instanceof Response; | |
} | |
protected function isHtmlResponse(Response $response) | |
{ | |
return strtolower(strtok($response->headers->get('Content-Type'), ';')) === 'text/html'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment