Skip to content

Instantly share code, notes, and snippets.

@davidcostadev
Last active May 24, 2018 22:06
Show Gist options
  • Save davidcostadev/d6e802777f616b05d26402bffc83f919 to your computer and use it in GitHub Desktop.
Save davidcostadev/d6e802777f616b05d26402bffc83f919 to your computer and use it in GitHub Desktop.
Compress output html afterRender view cakephp 3
<?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