ImageStyleDownloadController.php in ImageAPI Optimize WebP 2.x
File
src/Controller/ImageStyleDownloadController.php
View source
<?php
namespace Drupal\imageapi_optimize_webp\Controller;
use Drupal\image\Controller\ImageStyleDownloadController as CoreImageStyleDownloadController;
use Drupal\image\ImageStyleInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ImageStyleDownloadController extends CoreImageStyleDownloadController {
public function lookupSourceImage($image_uri) {
$source_image = substr($image_uri, 0, strrpos($image_uri, "."));
if ($source_image . '.webp' === $image_uri) {
return $source_image;
}
}
public function deliver(Request $request, $scheme, ImageStyleInterface $image_style) {
$target = $request->query
->get('file');
$path_info = pathinfo($target);
if ($path_info['extension'] == 'webp') {
$image_uri = $scheme . '://' . $target;
if ($source_uri = $this
->lookupSourceImage($image_uri)) {
$request->query
->set('file', str_replace($scheme . '://', '', $source_uri));
$source_response = parent::deliver($request, $scheme, $image_style);
$derivative_uri = $image_style
->buildUri($image_uri);
if ($source_response instanceof BinaryFileResponse) {
if (file_exists($derivative_uri)) {
$image = $this->imageFactory
->get($derivative_uri);
$uri = $image
->getSource();
$headers = [
'Content-Type' => 'image/webp',
'Content-Length' => $image
->getFileSize(),
];
return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
}
return new Response($this
->t('Error generating image.'), 500);
}
return $source_response;
}
throw new NotFoundHttpException();
}
else {
return parent::deliver($request, $scheme, $image_style);
}
}
}