You are here

protected function MinifyHTMLExit::minifyHtml in Minify Source HTML 8

Helper function to minify the HTML.

1 call to MinifyHTMLExit::minifyHtml()
MinifyHTMLExit::minify in src/EventSubscriber/MinifyHTMLExit.php
Helper function to minify HTML.

File

src/EventSubscriber/MinifyHTMLExit.php, line 329

Class

MinifyHTMLExit
Minifies the HTML of the response.

Namespace

Drupal\minifyhtml\EventSubscriber

Code

protected function minifyHtml() {
  $search = [];
  $replace = [];

  // Remove whitespaces after tags, except space.
  $search[] = '/\\>[^\\S ]+/s';
  $replace[] = '>';

  // Remove whitespaces before tags, except space.
  $search[] = '/[^\\S ]+\\</s';
  $replace[] = '<';

  // Shorten multiple whitespace sequences.
  $search[] = '/(\\s)+/s';
  $replace[] = '\\1';

  // Remove whitespaces around block/undisplayed elements.
  $search[] = '/\\s+(<\\/?(?:area|base(?:font)?|blockquote|body' . '|caption|center|col(?:group)?|dd|dir|div|dl|dt|fieldset|form' . '|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta' . '|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h||r|foot|itle)' . '|ul)\\b[^>]*>)/i';
  $replace[] = '$1';

  // Trim each line.
  $search[] = '/^\\s+|\\s+$/m';
  $replace[] = '';
  $minified = preg_replace($search, $replace, $this->content);

  // Only use minified content if there was not an error during minification.
  if (PREG_NO_ERROR === preg_last_error()) {
    $this->content = $minified;
  }
}