public function ImageStyleDownloadController::deliver in ImageAPI Optimize WebP 8
Same name and namespace in other branches
- 2.x src/Controller/ImageStyleDownloadController.php \Drupal\imageapi_optimize_webp\Controller\ImageStyleDownloadController::deliver()
Generates a derivative, given a style and image path.
After generating an image, transfer it to the requesting agent.
Parameters
\Symfony\Component\HttpFoundation\Request $request: The request object.
string $scheme: The file scheme, defaults to 'private'.
\Drupal\image\ImageStyleInterface $image_style: The image style to deliver.
Return value
\Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response The transferred file as response or some error response.
Throws
\Symfony\Component\HttpKernel\Exception\NotFoundHttpException Thrown when the file request is invalid.
\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException Thrown when the user does not have access to the file.
\Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException Thrown when the file is still being generated.
Overrides ImageStyleDownloadController::deliver
File
- src/
Controller/ ImageStyleDownloadController.php, line 36
Class
- ImageStyleDownloadController
- Defines a controller to serve image styles.
Namespace
Drupal\imageapi_optimize_webp\ControllerCode
public function deliver(Request $request, $scheme, ImageStyleInterface $image_style) {
$target = $request->query
->get('file');
$path_info = pathinfo($target);
// If .webp file, look for image to derive from.
if ($path_info['extension'] == 'webp') {
$image_uri = $scheme . '://' . $target;
// Continue processing if source found, else throw NotFoundHttpException.
if ($source_uri = $this
->lookupSourceImage($image_uri)) {
// Replace webp image with source image and call parent:deliver().
$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 parent:deliver() returns BinaryFileResponse, we'll replace
// the BinaryFileResponse with one containing the .webp image
// so long as it exists.
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' => filesize($image
->getToolkit()
->getResource()),
];
return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
}
// If the derivative does not exist, return a failed reponse.
return new Response($this
->t('Error generating image.'), 500);
}
// If we get any response other than BinaryFileResponse,
// then return the response unchanged.
return $source_response;
}
throw new NotFoundHttpException();
}
else {
return parent::deliver($request, $scheme, $image_style);
}
}