CacheableMetadata.php in Drupal 8
File
core/lib/Drupal/Core/Cache/CacheableMetadata.php
View source
<?php
namespace Drupal\Core\Cache;
class CacheableMetadata implements RefinableCacheableDependencyInterface {
use RefinableCacheableDependencyTrait;
public function getCacheTags() {
return $this->cacheTags;
}
public function setCacheTags(array $cache_tags) {
$this->cacheTags = $cache_tags;
return $this;
}
public function getCacheContexts() {
return $this->cacheContexts;
}
public function setCacheContexts(array $cache_contexts) {
$this->cacheContexts = $cache_contexts;
return $this;
}
public function getCacheMaxAge() {
return $this->cacheMaxAge;
}
public function setCacheMaxAge($max_age) {
if (!is_int($max_age)) {
throw new \InvalidArgumentException('$max_age must be an integer');
}
$this->cacheMaxAge = $max_age;
return $this;
}
public function merge(CacheableMetadata $other) {
$result = clone $this;
if (empty($this->cacheContexts)) {
$result->cacheContexts = $other->cacheContexts;
}
elseif (empty($other->cacheContexts)) {
$result->cacheContexts = $this->cacheContexts;
}
else {
$result->cacheContexts = Cache::mergeContexts($this->cacheContexts, $other->cacheContexts);
}
if (empty($this->cacheTags)) {
$result->cacheTags = $other->cacheTags;
}
elseif (empty($other->cacheTags)) {
$result->cacheTags = $this->cacheTags;
}
else {
$result->cacheTags = Cache::mergeTags($this->cacheTags, $other->cacheTags);
}
if ($this->cacheMaxAge === Cache::PERMANENT) {
$result->cacheMaxAge = $other->cacheMaxAge;
}
elseif ($other->cacheMaxAge === Cache::PERMANENT) {
$result->cacheMaxAge = $this->cacheMaxAge;
}
else {
$result->cacheMaxAge = Cache::mergeMaxAges($this->cacheMaxAge, $other->cacheMaxAge);
}
return $result;
}
public function applyTo(array &$build) {
$build['#cache']['contexts'] = $this->cacheContexts;
$build['#cache']['tags'] = $this->cacheTags;
$build['#cache']['max-age'] = $this->cacheMaxAge;
}
public static function createFromRenderArray(array $build) {
$meta = new static();
$meta->cacheContexts = isset($build['#cache']['contexts']) ? $build['#cache']['contexts'] : [];
$meta->cacheTags = isset($build['#cache']['tags']) ? $build['#cache']['tags'] : [];
$meta->cacheMaxAge = isset($build['#cache']['max-age']) ? $build['#cache']['max-age'] : Cache::PERMANENT;
return $meta;
}
public static function createFromObject($object) {
if ($object instanceof CacheableDependencyInterface) {
$meta = new static();
$meta->cacheContexts = $object
->getCacheContexts();
$meta->cacheTags = $object
->getCacheTags();
$meta->cacheMaxAge = $object
->getCacheMaxAge();
return $meta;
}
$meta = new static();
$meta->cacheMaxAge = 0;
return $meta;
}
}