Skip to content

Instantly share code, notes, and snippets.

@4rn0
Last active August 29, 2015 14:24
Show Gist options
  • Save 4rn0/8315ad5e1d99178c6755 to your computer and use it in GitHub Desktop.
Save 4rn0/8315ad5e1d99178c6755 to your computer and use it in GitHub Desktop.
Laravel 5 Minify middleware
<?php namespace App\Http\Middleware;
use Illuminate\Http\Response;
use Closure;
class Minify {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
if ($this->isResponse($response) && $this->isHtmlResponse($response))
{
$content = $response->getContent();
$content = preg_replace(['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], $content);
$content = preg_replace('<!--[^\[](.*?)-->', null, $content);
$response->setContent($content);
}
return $response;
}
/**
* Check if the response is a usable response class.
*
* @param mixed $response
*
* @return bool
*/
protected function isResponse($response)
{
return is_object($response) && $response instanceof Response;
}
/**
* Check if the content type header is html.
*
* @param \Illuminate\Http\Response $response
*
* @return bool
*/
protected function isHtmlResponse(Response $response)
{
$type = $response->headers->get('Content-Type');
return strtolower(strtok($type, ';')) === 'text/html';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment