Skip to content
Snippets Groups Projects
Commit 879f3436 authored by Alec Smrekar's avatar Alec Smrekar
Browse files

Add custom tag to cache entry

parent c739b137
No related branches found
No related tags found
No related merge requests found
......@@ -5,7 +5,9 @@ declare(strict_types=1);
namespace Drupal\menu_parser_php;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Menu\MenuLinkTreeElement;
......@@ -64,13 +66,22 @@ class RemoteMenuParser {
*
* @param string $url
* The URL at which the JSON linkset is available.
* @param \Drupal\Core\Cache\RefinableCacheableDependencyInterface|null $metadata
* Optional cache metadata.
*
* @return \Drupal\Core\Menu\MenuLinkTreeElement[]|null
* A tree of MenuLinkTreeElement objects. NULL on failure.
*/
public function readRemoteMenu(string $url): ?array {
public function readRemoteMenu(string $url, RefinableCacheableDependencyInterface $metadata = NULL): ?array {
$cached = $this->cacheBin->get($url);
if ($cached) {
if ($metadata) {
$tags = $cached->tags ?? [];
$expire = $cached->expire ?? Cache::PERMANENT;
$metadata->addCacheTags($tags);
$max_age = $expire - $this->time->getCurrentTime();
$metadata->mergeCacheMaxAge($max_age);
}
return $cached->data;
}
......@@ -100,7 +111,12 @@ class RemoteMenuParser {
else {
$expire = $this->time->getCurrentTime() + $expire_time_config;
}
$this->cacheBin->set($url, $data, $expire);
$cache_tags = [static::getCacheTag($url)];
$this->cacheBin->set($url, $data, $expire, $cache_tags);
if ($metadata) {
$metadata->mergeCacheMaxAge($expire_time_config);
$metadata->addCacheTags($cache_tags);
}
return $data;
}
......@@ -186,4 +202,18 @@ class RemoteMenuParser {
return '.' . implode('.', $hierarchy_array);
}
/**
* Generates a custom cache tag for a remote menu URL.
*
* @param string $url
* The URL.
*
* @return string
* The cache tag name.
*/
public static function getCacheTag(string $url): string {
$hash = substr(hash('sha256', $url), 30);
return 'menu_parser_php:menu:' . $hash;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment