View source  
  <?php
namespace Drupal\tinypng\Controller;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Image\ImageFactory;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\image\Controller\ImageStyleDownloadController;
use Drupal\image\ImageStyleInterface;
use Drupal\tinypng\TinyPngInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class TinyPngImageStyleDownloadController extends ImageStyleDownloadController {
  
  protected $tinyPng;
  
  protected $serviceLogger;
  
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('lock'), $container
      ->get('image.factory'), $container
      ->get('stream_wrapper_manager'), $container
      ->get('file_system'), $container
      ->get('logger.factory'), $container
      ->get('tinypng.compress'));
  }
  
  public function __construct(LockBackendInterface $lock, ImageFactory $image_factory, StreamWrapperManagerInterface $stream_wrapper_manager, FileSystemInterface $fs, LoggerChannelFactoryInterface $logger_factory, TinyPngInterface $tiny_png) {
    parent::__construct($lock, $image_factory, $stream_wrapper_manager, $fs);
    $this->serviceLogger = $logger_factory
      ->get('tinypng');
    $this->tinyPng = $tiny_png;
  }
  
  public function deliver(Request $request, $scheme, ImageStyleInterface $image_style) {
    
    if (!$image_style
      ->getThirdPartySetting('tinypng', 'tinypng_compress')) {
      return parent::deliver($request, $scheme, $image_style);
    }
    $target = $request->query
      ->get('file');
    $image_uri = $scheme . '://' . $target;
    
    $valid = !empty($image_style) && $this->streamWrapperManager
      ->isValidScheme($scheme);
    if (!$this
      ->config('image.settings')
      ->get('allow_insecure_derivatives') || strpos(ltrim($target, '\\/'), 'styles/') === 0) {
      $valid &= hash_equals($image_style
        ->getPathToken($image_uri), $request->query
        ->get(IMAGE_DERIVATIVE_TOKEN, ''));
    }
    if (!$valid) {
      
      throw new NotFoundHttpException();
    }
    $derivative_uri = $image_style
      ->buildUri($image_uri);
    $headers = [];
    
    if ($scheme == 'private') {
      $headers = $this
        ->moduleHandler()
        ->invokeAll('file_download', [
        $image_uri,
      ]);
      if (in_array(-1, $headers) || empty($headers)) {
        throw new AccessDeniedHttpException();
      }
    }
    
    if (!file_exists($image_uri)) {
      
      $path_info = pathinfo(StreamWrapperManager::getTarget($image_uri));
      $converted_image_uri = sprintf('%s://%s%s%s', $this->streamWrapperManager
        ->getScheme($derivative_uri), $path_info['dirname'], DIRECTORY_SEPARATOR, $path_info['filename']);
      if (!file_exists($converted_image_uri)) {
        $this->logger
          ->notice('Source image at %source_image_path not found while trying to generate derivative image at %derivative_path.', [
          '%source_image_path' => $image_uri,
          '%derivative_path' => $derivative_uri,
        ]);
        return new Response($this
          ->t('Error generating image, missing source file.'), 404);
      }
      else {
        
        $image_uri = $converted_image_uri;
      }
    }
    
    if (!file_exists($derivative_uri)) {
      $lock_name = 'image_style_deliver:' . $image_style
        ->id() . ':' . Crypt::hashBase64($image_uri);
      $lock_acquired = $this->lock
        ->acquire($lock_name);
      if (!$lock_acquired) {
        
        throw new ServiceUnavailableHttpException(3, 'Image generation in progress. Try again shortly.');
      }
    }
    
    $success = FALSE;
    if (file_exists($derivative_uri)) {
      $success = TRUE;
    }
    elseif ($image_style
      ->createDerivative($image_uri, $derivative_uri)) {
      $success = TRUE;
      try {
        $this->tinyPng
          ->setFromFile($derivative_uri);
        $res = $this->tinyPng
          ->saveTo($derivative_uri);
        $success = (bool) $res;
      } catch (\Exception $ex) {
        $this->serviceLogger
          ->error($ex
          ->getMessage());
      }
    }
    if (!empty($lock_acquired)) {
      $this->lock
        ->release($lock_name);
    }
    if ($success) {
      $image = $this->imageFactory
        ->get($derivative_uri);
      $uri = $image
        ->getSource();
      $headers += [
        'Content-Type' => $image
          ->getMimeType(),
        'Content-Length' => $image
          ->getFileSize(),
      ];
      
      return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
    }
    else {
      $this->logger
        ->notice('Unable to generate the derived image located at %path.', [
        '%path' => $derivative_uri,
      ]);
      return new Response($this
        ->t('Error generating image.'), 500);
    }
  }
}