custom/plugins/FroshPlatformHtmlMinify/src/Listener/ResponseListener.php line 23

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Frosh\HtmlMinify\Listener;
  3. use Frosh\HtmlMinify\Service\MinifyService;
  4. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\StreamedResponse;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. class ResponseListener
  9. {
  10.     private string $environment;
  11.     private MinifyService $minifyService;
  12.     public function __construct(string $environmentMinifyService $minifyService)
  13.     {
  14.         $this->environment $environment;
  15.         $this->minifyService $minifyService;
  16.     }
  17.     public function onKernelResponse(ResponseEvent $event): void
  18.     {
  19.         if ($this->environment !== 'prod') {
  20.             return;
  21.         }
  22.         if (!$event->isMainRequest()) {
  23.             return;
  24.         }
  25.         $response $event->getResponse();
  26.         if ($response instanceof BinaryFileResponse
  27.             || $response instanceof StreamedResponse) {
  28.             return;
  29.         }
  30.         if ($response->getStatusCode() === Response::HTTP_NO_CONTENT) {
  31.             return;
  32.         }
  33.         if (!str_contains($response->headers->get('Content-Type'''), 'text/html')) {
  34.             return;
  35.         }
  36.         $result $this->minifyService->minify($response->getContent(), $response->headers);
  37.         $response->setContent($result);
  38.     }
  39. }