addCacheableDependency example


  public function checkAccess(ContentEntityInterface $entity) {
    $result = AccessResult::allowed();

    $entity_type_id = $entity->getEntityTypeId();
    $result->addCacheableDependency($entity);
    // Add the cache dependencies used by     // ContentTranslationManager::isPendingRevisionSupportEnabled().     if (\Drupal::moduleHandler()->moduleExists('content_moderation')) {
      foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
        $result->addCacheableDependency($workflow);
      }
    }
    if (!ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id$entity->bundle())) {
      return $result;
    }

    

  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    if ($operation == 'delete' && $entity->isNew()) {
      return AccessResult::forbidden()->addCacheableDependency($entity);
    }
    if ($admin_permission = $this->entityType->getAdminPermission()) {
      return AccessResult::allowedIfHasPermission($account$admin_permission);
    }
    else {
      // No opinion.       return AccessResult::neutral();
    }
  }

  /** * Tries to retrieve a previously cached access value from the static cache. * * @param string $cid * Unique string identifier for the entity/operation, for example the * entity UUID or a custom string. * @param string $operation * The entity operation. Usually one of 'view', 'update', 'create' or * 'delete'. * @param string $langcode * The language code for which to check access. * @param \Drupal\Core\Session\AccountInterface $account * The user for which to check access. * * @return \Drupal\Core\Access\AccessResultInterface|null * The cached AccessResult, or NULL if there is no record for the given * user, operation, langcode and entity in the cache. */
$book_nids[] = $book['p' . $depth];
      $depth++;
    }
    /** @var \Drupal\node\NodeInterface[] $parent_books */
    $parent_books = $this->nodeStorage->loadMultiple($book_nids);
    $parent_books = array_map([$this->entityRepository, 'getTranslationFromContext']$parent_books);
    if (count($parent_books) > 0) {
      $depth = 1;
      while (!empty($book['p' . ($depth + 1)])) {
        if (!empty($parent_books[$book['p' . $depth]]) && ($parent_book = $parent_books[$book['p' . $depth]])) {
          $access = $parent_book->access('view', $this->account, TRUE);
          $breadcrumb->addCacheableDependency($access);
          if ($access->isAllowed()) {
            $breadcrumb->addCacheableDependency($parent_book);
            $links[] = $parent_book->toLink();
          }
        }
        $depth++;
      }
    }
    $breadcrumb->setLinks($links);
    $breadcrumb->addCacheContexts(['route.book_navigation']);
    return $breadcrumb;
  }
return $plugin;
  }

  /** * {@inheritdoc} */
  public function findByContext(array $contexts, RefinableCacheableDependencyInterface $cacheability) {
    $storage_types = array_keys($this->contextHandler->filterPluginDefinitionsByContexts($contexts$this->getDefinitions()));

    // Add the manager as a cacheable dependency in order to vary by changes to     // the plugin definitions.     $cacheability->addCacheableDependency($this);

    foreach ($storage_types as $type) {
      $plugin = $this->load($type$contexts);
      if ($plugin && $plugin->isApplicable($cacheability)) {
        return $plugin;
      }
    }
    return NULL;
  }

  /** * {@inheritdoc} */
'#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],
      '#items' => $results,
      '#empty' => [
        '#markup' => '<h3>' . $this->t('Your search yielded no results.') . '</h3>',
      ],
      '#list_type' => 'ol',
      '#context' => [
        'plugin' => $plugin->getPluginId(),
      ],
    ];

    $this->renderer->addCacheableDependency($build$entity);
    if ($plugin instanceof CacheableDependencyInterface) {
      $this->renderer->addCacheableDependency($build$plugin);
    }

    // If this plugin uses a search index, then also add the cache tag tracking     // that search index, so that cached search result pages are invalidated     // when necessary.     if ($plugin->getType()) {
      $build['search_results']['#cache']['tags'][] = 'search_index';
      $build['search_results']['#cache']['tags'][] = 'search_index:' . $plugin->getType();
    }

    
return AccessResult::allowedIfHasPermission($account, 'view test entity translations');
        }
      }
      if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
        return AccessResult::neutral('Unpublished entity');
      }
      return AccessResult::allowedIfHasPermission($account, 'view test entity');
    }
    elseif (in_array($operation['update', 'delete'])) {
      $access = AccessResult::allowedIfHasPermission($account, 'administer entity_test content');
      if (!$access->isAllowed() && $operation === 'update' && $account->hasPermission('edit own entity_test content')) {
        $access = $access->orIf(AccessResult::allowedIf($entity->getOwnerId() === $account->id()))->cachePerUser()->addCacheableDependency($entity);
      }
      return $access;
    }

    // Access to revisions is based on labels, so access can vary by individual     // revisions, since the 'name' field can vary by revision.     $labels = explode(',', $entity->label());
    $labels = array_map('trim', $labels);
    if (in_array($operation[
      'view all revisions',
      'view revision',
    ],

    }

    // Only check access if the component is not being previewed.     if ($event->inPreview()) {
      $access = AccessResult::allowed()->setCacheMaxAge(0);
    }
    else {
      $access = $block->access($this->currentUser, TRUE);
    }

    $event->addCacheableDependency($access);
    if ($access->isAllowed()) {
      $event->addCacheableDependency($block);

      // @todo Revisit after https://www.drupal.org/node/3027653, as this will       // provide a better way to remove contextual links from Views blocks.       // Currently, doing this requires setting       // \Drupal\views\ViewExecutable::$showAdminLinks() to false before the       // Views block is built.       if ($block instanceof ViewsBlock && $event->inPreview()) {
        $block->getViewExecutable()->setShowAdminLinks(FALSE);
      }

      
'#type' => 'link',
        '#title' => t('Edit shortcuts'),
        '#url' => Url::fromRoute('entity.shortcut_set.customize_form', ['shortcut_set' => $shortcut_set->id()]),
        '#options' => ['attributes' => ['class' => ['edit-shortcuts']]],
      ];
    }

    $build = [
      'shortcuts' => $links,
      'configure' => $configure_link,
    ];
    $this->renderer->addCacheableDependency($build$shortcut_set);

    return $build;
  }

}
      // 2. Some Config entities choose to not use the cache tag that the under-       // lying Config object provides by default (For performance and       // cacheability reasons it may not make sense to have a unique cache       // tag for every Config entity. The DateFormat Config entity specifies       // the 'rendered' cache tag for example, because A) date formats are       // changed extremely rarely, so invalidating all render cache items is       // fine, B) it means fewer cache tags per page.).       // 3. Fewer cache tags is better for performance.       $self_referring_cache_tag = ['config:' . $configs[$id]->getName()];
      $config_cacheability = CacheableMetadata::createFromObject($configs[$id]);
      $config_cacheability->setCacheTags(array_diff($config_cacheability->getCacheTags()$self_referring_cache_tag));
      $entity->addCacheableDependency($config_cacheability);
    }

    return $entities;
  }

  /** * {@inheritdoc} */
  protected function doCreate(array $values) {
    // Set default language to current language if not provided.     $values += [$this->langcodeKey => $this->languageManager->getCurrentLanguage()->getId()];
    
/** @var \Drupal\Core\Entity\EntityInterface $entity */
    if ($entity = $field_item->get('entity')->getValue()) {
      $values['target_type'] = $entity->getEntityTypeId();
      // Add the target entity UUID to the normalized output values.       $values['target_uuid'] = $entity->uuid();

      // Add a 'url' value if there is a reference and a canonical URL. Hard       // code 'canonical' here as config entities override the default $rel       // parameter value to 'edit-form.       if ($entity->hasLinkTemplate('canonical') && !$entity->isNew() && $url = $entity->toUrl('canonical')->toString(TRUE)) {
        $this->addCacheableDependency($context$url);
        $values['url'] = $url->getGeneratedUrl();
      }
      // @todo Remove in https://www.drupal.org/project/drupal/issues/2925520       elseif ($entity instanceof FileInterface) {
        $values['url'] = $entity->createFileUrl(FALSE);
      }
    }

    return $values;
  }

  
/** * {@inheritdoc} */
  public function getCacheableMetadata($entity_type_id = NULL) {
    if (!$entity_type_id) {
      throw new \LogicException('Missing entity type ID');
    }

    $cacheable_metadata = new CacheableMetadata();
    if ($display = $this->getDisplay($entity_type_id)) {
      $cacheable_metadata->addCacheableDependency($display);
    }
    return $cacheable_metadata;
  }

  /** * Returns the entity view display for a given entity type and view mode. * * @param string $entity_type_id * The entity type ID. * * @return \Drupal\layout_builder\Entity\LayoutEntityDisplayInterface|null * The entity view display, if it exists. */


  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    if ($shortcut_set = $this->shortcutSetStorage->load($entity->bundle())) {
      return shortcut_set_edit_access($shortcut_set);
    }
    // @todo Fix this bizarre code: how can a shortcut exist without a shortcut     // set? The above if-test is unnecessary. See https://www.drupal.org/node/2339903.     return AccessResult::neutral()->addCacheableDependency($entity);
  }

  /** * {@inheritdoc} */
  protected function checkCreateAccess(AccountInterface $account, array $context$entity_bundle = NULL) {
    if ($shortcut_set = $this->shortcutSetStorage->load($entity_bundle)) {
      return shortcut_set_edit_access($shortcut_set);
    }
    // @todo Fix this bizarre code: how can a shortcut exist without a shortcut     // set? The above if-test is unnecessary. See https://www.drupal.org/node/2339903.
// Generate tokens for the anonymous user.     $anonymous_user = User::load(0);
    $tests = [];
    $tests['[user:uid]'] = 'not yet assigned';
    $tests['[user:display-name]'] = $anonymous_user->getDisplayName();

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($anonymous_user);
    $metadata_tests = [];
    $metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
    $metadata_tests['[user:display-name]'] = $bubbleable_metadata;

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_service->replace($input['user' => $anonymous_user]['langcode' => $language_interface->getId()]$bubbleable_metadata);
      $this->assertSame((string) $expected(string) $output, "Failed test case: {$input}");
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Generate login and cancel link.     $tests = [];
    

function hook_block_access(\Drupal\block\Entity\Block $block$operation, \Drupal\Core\Session\AccountInterface $account) {
  // Example code that would prevent displaying the 'Powered by Drupal' block in   // a region different than the footer.   if ($operation == 'view' && $block->getPluginId() == 'system_powered_by_block') {
    return AccessResult::forbiddenIf($block->getRegion() != 'footer')->addCacheableDependency($block);
  }

  // No opinion.   return AccessResult::neutral();
}

/** * Allow modules to alter the block plugin definitions. * * @param array[] $definitions * The array of block definitions, keyed by plugin ID. * * @ingroup block_api */


    // Administrators can view/update/delete all user profiles.     if ($account->hasPermission('administer users')) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    switch ($operation) {
      case 'view':
        // Only allow view access if the account is active.         if ($account->hasPermission('access user profiles') && $entity->isActive()) {
          return AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
        }
        // Users can view own profiles at all times.         elseif ($account->id() == $entity->id()) {
          return AccessResult::allowed()->cachePerUser();
        }
        else {
          return AccessResultNeutral::neutral("The 'access user profiles' permission is required and the user must be active.")->cachePerPermissions()->addCacheableDependency($entity);
        }
        break;

      case 'update':
        
Home | Imprint | This part of the site doesn't use cookies.