Skip to content

Instantly share code, notes, and snippets.

@alexfinnarn
Created September 15, 2023 17:37
Show Gist options
  • Save alexfinnarn/ed0b05dfaea40fd9ccfebd9980d7bb7b to your computer and use it in GitHub Desktop.
Save alexfinnarn/ed0b05dfaea40fd9ccfebd9980d7bb7b to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\your_module\StackMiddleware;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Reduces the number of cache tags in the response.
*/
class CacheTagsControlMiddleware implements HttpKernelInterface {
/**
* The wrapped HTTP kernel.
*
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $httpKernel;
/**
* Constructs a new CacheTagsControlMiddleware object.
*
* @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
* The HTTP kernel.
*/
public function __construct(HttpKernelInterface $http_kernel) {
$this->httpKernel = $http_kernel;
}
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
$response = $this->httpKernel->handle($request, $type, $catch);
// This could be replaced by config and cached...which I think config is cached by default.
// Or some other way of filtering requests can be used.
$path = $request->getPathInfo();
$paths_to_control = [
'/a/path',
];
$max_tags = 625;
if (in_array($path, $paths_to_control)) {
$edge_cache_tags = $response->headers->get('edge-cache-tag');
if ($edge_cache_tags) {
$tags_array = explode(',', $edge_cache_tags);
if (count($tags_array) > $max_tags) {
$tags_array = array_slice($tags_array, 0, $max_tags);
$response->headers->set('edge-cache-tag', implode(',', $tags_array));
}
}
$purge_cache_tags = $response->headers->get('x-acquia-purge-tags');
if ($purge_cache_tags) {
$tags_array = explode(' ', $purge_cache_tags);
if (count($tags_array) > $max_tags) {
$tags_array = array_slice($tags_array, 0, $max_tags);
$response->headers->set('x-acquia-purge-tags', implode(' ', $tags_array));
}
}
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment