You are here

protected function MenuTreeResource::addLinkCacheDependencies in REST Menu Tree 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/rest/resource/MenuTreeResource.php \Drupal\rest_menu_tree\Plugin\rest\resource\MenuTreeResource::addLinkCacheDependencies()

Add Cache Tags.

1 call to MenuTreeResource::addLinkCacheDependencies()
MenuTreeResource::addCacheDependencies in src/Plugin/rest/resource/MenuTreeResource.php
Add Cache Tags.

File

src/Plugin/rest/resource/MenuTreeResource.php, line 216

Class

MenuTreeResource
Provides a resource to get view modes by entity and bundle.

Namespace

Drupal\rest_menu_tree\Plugin\rest\resource

Code

protected function addLinkCacheDependencies(MenuLinkInterface $link, CacheableResponseInterface $response) {
  $entity_type = NULL;
  $entity_type_id = $link
    ->getBaseId();
  $uuid = $link
    ->getDerivativeId();
  if ($link instanceof EntityInterface) {
    $entity_type = $link
      ->getEntityType();
  }
  else {
    try {
      $entity_type = $this->entityTypeManager
        ->getDefinition($entity_type_id);
    } catch (\Exception $e) {

      // Silence is golden.
    }
  }
  if (!$entity_type) {
    return;
  }

  // Add the list cache tags.
  $cache = new CacheableMetadata();
  $cache
    ->addCacheTags($entity_type
    ->getListCacheTags());
  $response
    ->addCacheableDependency($cache);

  // If the link is an entity already, the cache tags were added in
  // ::addCacheDependencies().
  if ($link instanceof EntityInterface) {
    return;
  }

  // Get the entity.
  $entity = NULL;
  $storage = $this->entityTypeManager
    ->getStorage($entity_type_id);
  $metadata = $link
    ->getMetaData();
  if (!empty($metadata['entity_id'])) {
    $entity = $storage
      ->load($metadata['entity_id']);
  }
  else {
    $entities = $storage
      ->loadByProperties([
      $entity_type
        ->getKey('uuid') => $uuid,
    ]);
    $entity = reset($entities);
  }
  if (!$entity) {
    return;
  }
  $response
    ->addCacheableDependency($entity);
}