Reusing metadata from data retrieved from caches in newly generated cache metadata can lead to max-age drift. This problem has been observed in various core subsystems, e.g., Render Cache, Dynamic Page Cache and JSON:API.
A static Cache::ttlFromExpire() helper method is now available on the Drupal\Core\Cache\Cache utility class to mitigate this problem. Use it in caches to adapt the max-age of returned cache entries that can carry one, typically render arrays or implementations of CacheableDependencyInterface.
Anyone using the cached data from said caches will now receive a correct max age after this change and therefore does not need to update their code.
Example
Applies for caches where data is a render array.
Before
public function get(string $key) {
$item = $this->cache->get($key);
if ($item !== NULL) {
// Modify, store or deliver response
}
}
After
public function get(string $key) {
$item = $this->cache->get($key);
if ($item !== NULL) {
$cacheability = CacheableMetadata::createFromRenderArray($item->data);
$cacheability->setCacheMaxAge(Cache::ttlFromExpire($item->expire));
$cacheability->applyTo($item->data);
// Modify, store or deliver response
}
}
Again, if your returned cache entry does not somehow carry a max age, you do not need to adjust your cache's code.