Skip to content
Snippets Groups Projects
Commit 40c92161 authored by Robert Bryan's avatar Robert Bryan
Browse files

replaced old code with improved code

parent bfd658c8
Branches 3.x
1 merge request!22replaced old code with improved code
services:
imageapi_optimize_webp.route_subscriber:
class: Drupal\imageapi_optimize_webp\Routing\RouteSubscriber
arguments: ['@module_handler']
tags:
- { name: event_subscriber }
\ No newline at end of file
......@@ -51,11 +51,16 @@ function imageapi_optimize_webp_responsive_preprocess_responsive_image(&$variabl
$image_uri = $image_style->buildUri($variables['uri']);
$image_url = \Drupal::service('file_url_generator')->generateAbsoluteString($image_uri);
$image_relative_path = \Drupal::service('file_url_generator')->transformRelative($image_url);
$image_token = $image_style->getPathToken($variables['uri']);
$image_relative_path .= '?itok=' . $image_token;
$image_relative_path_file = explode('?', $image_relative_path)[0];
$webp_relative_path = str_replace($image_relative_path_file,
$image_relative_path_file . '.webp', $image_relative_path);
$image_style_map[$image_relative_path] = $webp_relative_path;
$image_webp_uri = $image_style->buildUri($variables['uri'] . '.webp');
$image_webp_url = \Drupal::service('file_url_generator')->generateAbsoluteString($image_webp_uri);
$image_webp_relative_path = \Drupal::service('file_url_generator')->transformRelative($image_webp_url);
$image_webp_token = $image_style->getPathToken($variables['uri'] . '.webp');
$image_webp_relative_path .= '?itok=' . $image_webp_token;
$image_style_map[$image_relative_path] = $image_webp_relative_path;
}
}
}
......
<?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;
/**
* Defines a controller to serve image styles.
*/
class ImageStyleDownloadController extends CoreImageStyleDownloadController {
/**
* Lookup potential source files based on webp uri.
*
* @param string $image_uri
* The webp image uri.
*
* @return mixed|null
* The source image uri.
*/
public function lookupSourceImage($image_uri) {
$source_image = substr($image_uri, 0, strrpos($image_uri, "."));
if($source_image . '.webp' === $image_uri) {
return $source_image;
}
}
/**
* {@inheritdoc}
*/
public function deliver(Request $request, $scheme, ImageStyleInterface $image_style, string $required_derivative_scheme) {
$target = $request->query->get('file');
if (!$target) {
throw new NotFoundHttpException();
}
$path_info = pathinfo($target);
// If .webp file, look for image to derive from.
if (isset($path_info['extension']) && $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, $required_derivative_scheme);
$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' => $image->getFileSize(),
];
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, $required_derivative_scheme);
}
}
}
......@@ -3,7 +3,7 @@
namespace Drupal\imageapi_optimize_webp\Entity;
use Drupal\imageapi_optimize\Entity\ImageAPIOptimizePipeline;
use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
/**
* Wrap ImageAPIOptimizePipeline to copy webp derivative to proper directory.
......@@ -34,7 +34,7 @@ class ImageAPIOptimizeWebPPipeline extends ImageAPIOptimizePipeline {
foreach ($this->temporaryFiles as $temp_image_uri) {
$temp_webp_uri = $temp_image_uri . '.webp';
if (file_exists($temp_webp_uri)) {
$temp_image_uri = \Drupal::service('file_system')->copy($temp_webp_uri, $webp_uri, FileExists::Rename);
$temp_image_uri = \Drupal::service('file_system')->copy($temp_webp_uri, $webp_uri, FileSystemInterface::EXISTS_RENAME);
if ($temp_image_uri) {
$this->temporaryFiles[] = $temp_webp_uri;
break;
......
......@@ -19,13 +19,12 @@ class WebP extends ConfigurableImageAPIOptimizeProcessorBase {
*/
public function applyToImage($image_uri) {
$source_image = $this->imageFactory->get($image_uri, 'gd');
if ($source_image) {
$destination = $image_uri . '.webp';
// @todo: Add try/catch.
imagewebp($source_image->getToolkit()->getResource(), $destination, $this->configuration['quality']);
$file_type = pathinfo($image_uri, PATHINFO_EXTENSION);
if ($file_type == 'webp' && $source_image->getToolkit()->getMimeType() != 'image/webp') {
imagewebp($source_image->getToolkit()->getImage(), $image_uri, $this->configuration['quality']);
// Fix issue where sometimes image fails to generate.
if (filesize($destination) % 2 == 1) {
file_put_contents($destination, "\0", FILE_APPEND);
if (filesize($image_uri) % 2 == 1) {
file_put_contents($image_uri, "\0", FILE_APPEND);
}
return TRUE;
}
......
<?php
namespace Drupal\imageapi_optimize_webp\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Class RouteSubscriber.
*
* Override 'image.style_public' controller to handle .webp deriver.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('image.style_public')) {
$route->setDefault('_controller', 'Drupal\imageapi_optimize_webp\Controller\ImageStyleDownloadController::deliver');
}
if ($route = $collection->get('image.style_private')) {
$route->setDefault('_controller', 'Drupal\imageapi_optimize_webp\Controller\ImageStyleDownloadController::deliver');
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment