checkAccess example

case 'access taxonomy overview':
      case 'view':
        return AccessResult::allowedIfHasPermissions($account['access taxonomy overview', 'administer taxonomy'], 'OR');

      case 'reset all weights':
        return AccessResult::allowedIfHasPermissions($account[
          'administer taxonomy',
          'edit terms in ' . $entity->id(),
        ], 'OR');

      default:
        return parent::checkAccess($entity$operation$account);
    }
  }

}
    // - At least one module says to grant access.     $access = array_merge(
      $this->moduleHandler()->invokeAll('entity_access', [$entity$operation$account]),
      $this->moduleHandler()->invokeAll($entity->getEntityTypeId() . '_access', [$entity$operation$account])
    );

    $return = $this->processAccessHookResults($access);

    // Also execute the default access check except when the access result is     // already forbidden, as in that case, it can not be anything else.     if (!$return->isForbidden()) {
      $return = $return->orIf($this->checkAccess($entity$operation$account));
    }
    $result = $this->setCache($return$cid$operation$langcode$account);
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * Determines entity access. * * We grant access to the entity if both of these conditions are met: * - No modules say to deny access. * - At least one module says to grant access. * * @param \Drupal\Core\Access\AccessResultInterface[] $access * An array of access results of the fired access hook. * * @return \Drupal\Core\Access\AccessResultInterface * The combined result of the various access checks' results. All their * cacheability metadata is merged as well. * * @see \Drupal\Core\Access\AccessResultInterface::orIf() */
'outdated' => $metadata->isOutdated(),
              ],
            ],
          ];

          if ($is_original) {
            $language_name = $this->t('<strong>@language_name (Original language)</strong>', ['@language_name' => $language_name]);
            $source_name = $this->t('n/a');
          }
          else {
            /** @var \Drupal\Core\Access\AccessResultInterface $delete_route_access */
            $delete_route_access = \Drupal::service('content_translation.delete_access')->checkAccess($translation);
            $cacheability->addCacheableDependency($delete_route_access);

            if ($delete_route_access->isAllowed()) {
              $source_name = isset($languages[$source]) ? $languages[$source]->getName() : $this->t('n/a');
              $delete_access = $entity->access('delete', NULL, TRUE);
              $translation_access = $handler->getTranslationAccess($entity, 'delete');
              $cacheability
                ->addCacheableDependency($delete_access)
                ->addCacheableDependency($translation_access);

              if ($delete_access->isAllowed() && $entity_type->hasLinkTemplate('delete-form')) {
                
foreach ($items as $delta => $item) {
      // Ignore items where no entity could be loaded in prepareView().       if (!empty($item->_loaded)) {
        $entity = $item->entity;

        // Set the entity in the correct language for display.         if ($entity instanceof TranslatableInterface) {
          $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity$langcode);
        }

        $access = $this->checkAccess($entity);
        // Add the access result's cacheability, ::view() needs it.         $item->_accessCacheability = CacheableMetadata::createFromObject($access);
        if ($access->isAllowed()) {
          // Add the referring item, in case the formatter needs it.           $entity->_referringItem = $items[$delta];
          $entities[$delta] = $entity;
        }
      }
    }

    return $entities;
  }
$target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
          $is_new_translation = ($source_language->getId() != $target_language->getId()
            && isset($languages[$source_language->getId()])
            && isset($languages[$target_language->getId()])
            && !isset($translations[$target_language->getId()]));
          return AccessResult::allowedIf($is_new_translation)->cachePerPermissions()->addCacheableDependency($entity)
            ->andIf($handler->getTranslationAccess($entity$operation));

        case 'delete':
          // @todo Remove this in https://www.drupal.org/node/2945956.           /** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
          $delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
          $access = $this->checkAccess($entity$language$operation);
          return $delete_access->andIf($access);

        case 'update':
          return $this->checkAccess($entity$language$operation);
      }
    }

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

  
use Drupal\Core\Session\AccountInterface;

/** * Provides en entity access control handler for base field override entity. */
class BaseFieldOverrideAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    $access = parent::checkAccess($entity$operation$account);
    return $access->orIf(AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields'));
  }

}
if (!$this->currentUser()->hasPermission('administer modules')) {
              $theme->insufficient_module_permissions = TRUE;
            }
          }
        }
      }

      $theme->operations = [];
      if (!empty($theme->status) || !$theme->info['core_incompatible'] && !$theme->incompatible_php && !$theme->incompatible_base && !$theme->incompatible_engine && !$theme->incompatible_module && empty($theme->module_dependencies_disabled)) {
        // Create the operations links.         $query['theme'] = $theme->getName();
        if ($this->themeAccess->checkAccess($theme->getName())) {
          $theme->operations[] = [
            'title' => $this->t('Settings'),
            'url' => Url::fromRoute('system.theme_settings_theme', ['theme' => $theme->getName()]),
            'attributes' => ['title' => $this->t('Settings for @theme theme', ['@theme' => $theme->info['name']])],
          ];
        }
        if (!empty($theme->status)) {
          if (!$theme->is_default) {
            $theme_uninstallable = TRUE;
            if ($theme->getName() == $admin_theme) {
              $theme_uninstallable = FALSE;
            }
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\search\SearchPageInterface $entity */
    if (in_array($operation['delete', 'disable'])) {
      if ($entity->isDefaultSearch()) {
        return AccessResult::forbidden()->addCacheableDependency($entity);
      }
      else {
        return parent::checkAccess($entity$operation$account)->addCacheableDependency($entity);
      }
    }
    if ($operation == 'view') {
      if (!$entity->status()) {
        return AccessResult::forbidden()->addCacheableDependency($entity);
      }
      $plugin = $entity->getPlugin();
      if ($plugin instanceof AccessibleInterface) {
        return $plugin->access($operation$account, TRUE)->addCacheableDependency($entity);
      }
      return AccessResult::allowed()->addCacheableDependency($entity);
    }
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    switch ($operation) {
      case 'delete':
        if ($entity->id() == RoleInterface::ANONYMOUS_ID || $entity->id() == RoleInterface::AUTHENTICATED_ID) {
          return AccessResult::forbidden();
        }

      default:
        return parent::checkAccess($entity$operation$account);
    }
  }

}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
    // This formatter is only available for entity types that reference     // media items.     return ($field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'media');
  }

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity) {
    return $entity->access('view', NULL, TRUE)
      ->andIf(parent::checkAccess($entity));
  }

  /** * Get the URL for the media thumbnail. * * @param \Drupal\media\MediaInterface $media * The media item. * @param \Drupal\Core\Entity\EntityInterface $entity * The entity that the field belongs to. * * @return \Drupal\Core\Url|null * The URL object for the media item or null if we don't want to add * a link. */


  /** * {@inheritdoc} */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    foreach ($this->negotiators as $negotiator_id) {
      $negotiator = $this->classResolver->getInstanceFromDefinition($negotiator_id);

      if ($negotiator->applies($route_match)) {
        $theme = $negotiator->determineActiveTheme($route_match);
        if ($theme !== NULL && $this->themeAccess->checkAccess($theme)) {
          return $theme;
        }
      }
    }
  }

}
'user.logout', []$this->currentUser, TRUE, AccessResult::allowed()],
      ]);

    $this->mockTree();
    $this->originalTree[5]->subtree[7]->access = AccessResult::neutral();
    $this->cacheContextManager->assertValidTokens(['user'])->shouldBeCalled()->willReturn(TRUE);
    $this->originalTree[8]->access = AccessResult::allowed()->cachePerUser();

    // Since \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators::checkAccess()     // allows access to any link if the user has the 'link to any page'     // permission, *every* single access result is varied by permissions.     $tree = $this->defaultMenuTreeManipulators->checkAccess($this->originalTree);

    // Menu link 1: route without parameters, access forbidden, but at level 0,     // hence kept.     $element = $tree[1];
    $this->assertEquals(AccessResult::forbidden()->cachePerPermissions()$element->access);
    $this->assertInstanceOf('\Drupal\Core\Menu\InaccessibleMenuLink', $element->link);
    // Menu link 2: route with parameters, access granted.     $element = $tree[2];
    $this->assertEquals(AccessResult::allowed()->cachePerPermissions()$element->access);
    $this->assertNotInstanceOf('\Drupal\Core\Menu\InaccessibleMenuLink', $element->link);
    // Menu link 3: route with parameters, AccessResult::neutral(), top-level

class LanguageAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    switch ($operation) {
      case 'view':
        return parent::checkAccess($entity$operation$account);

      case 'update':
        /** @var \Drupal\Core\Language\LanguageInterface $entity */
        return AccessResult::allowedIf(!$entity->isLocked())->addCacheableDependency($entity)
          ->andIf(parent::checkAccess($entity$operation$account));

      case 'delete':
        /** @var \Drupal\Core\Language\LanguageInterface $entity */
        return AccessResult::allowedIf(!$entity->isLocked())->addCacheableDependency($entity)
          ->andIf(AccessResult::allowedIf(!$entity->isDefault())->addCacheableDependency($entity))
          ->andIf(parent::checkAccess($entity$operation$account));

      

  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    switch ($operation) {
      case 'view':
        return AccessResult::allowedIfHasPermission($account, 'access content');

      case 'delete':
        if ($entity->isLocked()) {
          return AccessResult::forbidden()->addCacheableDependency($entity);
        }
        else {
          return parent::checkAccess($entity$operation$account)->addCacheableDependency($entity);
        }
        break;

      default:
        return parent::checkAccess($entity$operation$account);

    }
  }

}

  protected $viewLabelOperation = TRUE;

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    if ($operation === 'view label') {
      return AccessResult::allowedIfHasPermission($account, 'view media');
    }
    else {
      return parent::checkAccess($entity$operation$account);
    }
  }

}
Home | Imprint | This part of the site doesn't use cookies.