cloudflare_image_style-8.x-1.x-dev/src/PathProcessor/CloudflarePathProcessorImageStyles.php
src/PathProcessor/CloudflarePathProcessorImageStyles.php
<?php
namespace Drupal\cloudflare_image_style\PathProcessor;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines a path processor to rewrite image styles URLs.
*
* As the route system does not allow arbitrary amount of parameters convert
* the file path to a query parameter on the request.
*
* This processor handles two different cases:
* - public image styles: In order to allow the webserver to serve these files
* directly, the route is registered under the same path as the image style so
* it took over the first generation. Therefore the path processor converts
* the file path to a query parameter.
* - private image styles: In contrast to public image styles, private
* derivatives are already using system/files/styles. Similar to public image
* styles, it also converts the file path to a query parameter.
*/
class CloudflarePathProcessorImageStyles implements InboundPathProcessorInterface {
/**
* The stream wrapper manager service.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
*/
protected $streamWrapperManager;
/**
* Constructs a new PathProcessorImageStyles object.
*
* @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
* The stream wrapper manager service.
*/
public function __construct(StreamWrapperManagerInterface $stream_wrapper_manager) {
$this->streamWrapperManager = $stream_wrapper_manager;
}
/**
* {@inheritdoc}
*/
public function processInbound($path, Request $request) {
if (strpos($path, '/cdn-cgi/image/') !== 0) {
return $path;
}
// Strip out path prefix.
$rest = explode('/', str_replace('/cdn-cgi/image/', '', $path));
$style = array_shift($rest);
// Set the file as query parameter.
$request->query->set('file', implode('/', $rest));
return '/cdn-cgi/image/' . $style;
}
}
