You are here

public function MinifyHTMLExit::response in Minify Source HTML 8

Minifies the HTML.

Parameters

\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event: Response event object.

File

src/EventSubscriber/MinifyHTMLExit.php, line 102

Class

MinifyHTMLExit
Minifies the HTML of the response.

Namespace

Drupal\minifyhtml\EventSubscriber

Code

public function response(FilterResponseEvent $event) {
  if (!$this->abort && $this->config
    ->get('minifyhtml.config')
    ->get('minify')) {
    $response = $event
      ->getResponse();

    // Make sure that the following render classes are the only ones that
    // are minified.
    $allowed_response_classes = [
      'Drupal\\big_pipe\\Render\\BigPipeResponse',
      'Drupal\\Core\\Render\\HtmlResponse',
    ];
    if (in_array(get_class($response), $allowed_response_classes)) {
      $this->content = $response
        ->getContent();
      $this
        ->minify();

      // If, for some reason, the minification failed and some artifacts
      // still remain in the source this will cause a mostly white unusable
      // page. The fallback for this scenario is to revert and notify.
      if (strpos($this->content, '%' . $this->token)) {
        $this->logger
          ->get('minifyhtml')
          ->warning('Minifyhtml failed.');
      }
      else {
        $response
          ->setContent($this->content);
      }
    }
  }
}