Last active
May 24, 2018 22:06
-
-
Save davidcostadev/d6e802777f616b05d26402bffc83f919 to your computer and use it in GitHub Desktop.
Compress output html afterRender view cakephp 3
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\View; | |
use Cake\View\View; | |
use Cake\Event\Event; | |
class AppView extends View | |
{ | |
public function initialize() { | |
$this->eventManager()->on('View.afterLayout', [$this, 'afterLayout']); | |
} | |
public function afterLayout(Event $event) { | |
$pageHtml = $event->subject()->Blocks->get('content'); | |
$pageHtmlCompressed = $this->sanitize_output($pageHtml); | |
$event->subject()->Blocks->set('content', $pageHtmlCompressed); | |
} | |
public function sanitize_output($buffer) { | |
$search = array( | |
'/\>[^\S ]+/s', // strip whitespaces after tags, except space | |
'/[^\S ]+\</s', // strip whitespaces before tags, except space | |
'/(\s)+/s', // shorten multiple whitespace sequences | |
'<!--(.*?)-->' | |
); | |
$replace = array( | |
'>', | |
'<', | |
'\\1' | |
); | |
$buffer = preg_replace($search, $replace, $buffer); | |
$buffer = str_replace('<>', '', $buffer); | |
return $buffer; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment