hasPermission example

    // than checking to see if the page exists, which is costly.     if ($this->moduleHandler->moduleExists('help') && $module->status && $this->moduleHandler->hasImplementations('help', $module->getName())) {
      $row['links']['help'] = [
        '#type' => 'link',
        '#title' => $this->t('Help <span class="visually-hidden">for @module</span>', ['@module' => $module->info['name']]),
        '#url' => Url::fromRoute('help.page', ['name' => $module->getName()]),
        '#options' => ['attributes' => ['class' => ['module-link', 'module-link-help']]],
      ];
    }

    // Generate link for module's permission, if the user has access to it.     if ($module->status && $this->currentUser->hasPermission('administer permissions') && $this->permissionHandler->moduleProvidesPermissions($module->getName())) {
      $row['links']['permissions'] = [
        '#type' => 'link',
        '#title' => $this->t('Permissions <span class="visually-hidden">for @module</span>', ['@module' => $module->info['name']]),
        '#url' => Url::fromRoute('user.admin_permissions.module', ['modules' => $module->getName()]),
        '#options' => ['attributes' => ['class' => ['module-link', 'module-link-permissions']]],
      ];
    }

    // Generate link for module's configuration page, if it has one.     if ($module->status && isset($module->info['configure'])) {
      $route_parameters = $module->info['configure_parameters'] ?? [];
      
$entity_type,
      $container->get('entity_type.manager'),
    );
  }

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\media\MediaInterface $entity */
    // Allow admin permission to override all operations.     if ($account->hasPermission($this->entityType->getAdminPermission())) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    $type = $entity->bundle();
    $is_owner = ($account->id() && $account->id() === $entity->getOwnerId());
    switch ($operation) {
      case 'view':
        if ($entity->isPublished()) {
          $access_result = AccessResult::allowedIf($account->hasPermission('view media'))
            ->cachePerPermissions()
            ->addCacheableDependency($entity);
          
return $operations;
  }

  /** * {@inheritdoc} */
  public function buildHeader() {
    $header['label'] = t('Vocabulary name');
    $header['description'] = t('Description');

    if ($this->currentUser->hasPermission('administer vocabularies') && !empty($this->weightKey)) {
      $header['weight'] = t('Weight');
    }

    return $header + parent::buildHeader();
  }

  /** * {@inheritdoc} */
  public function buildRow(EntityInterface $entity) {
    $row['label'] = $entity->label();
    

    elseif ($info_url = $this->getInfoUrl($status_code)) {
      $error['links']['info']['href'] = $info_url;
    }
    // Exceptions thrown without an explicitly defined code get assigned zero by     // default. Since this is no helpful information, omit it.     if ($exception->getCode() !== 0) {
      $error['code'] = (string) $exception->getCode();
    }

    $is_verbose_reporting = \Drupal::config('system.logging')->get('error_level') === ERROR_REPORTING_DISPLAY_VERBOSE;
    $site_report_access = $this->currentUser->hasPermission('access site reports');
    if ($site_report_access && $is_verbose_reporting) {
      // The following information may contain sensitive information. Only show       // it to authorized users.       $error['source'] = [
        'file' => $exception->getFile(),
        'line' => $exception->getLine(),
      ];
      $error['meta'] = [
        'exception' => (string) $exception,
        'trace' => $exception->getTrace(),
      ];
    }
if ($current_perm === 'administer blocks') {
    $config->set('display.default.display_options.access.options.perm', 'access block library')
      ->save(TRUE);
  }
}

/** * Update permissions for users with "administer blocks" permission. */
function block_content_post_update_sort_permissions(&$sandbox = NULL) {
  \Drupal::classResolver(ConfigEntityUpdater::class)->update($sandbox, 'user_role', function DRole $role) {
    if ($role->hasPermission('administer blocks')) {
      $role->grantPermission('administer block content');
      $role->grantPermission('access block library');
      $role->grantPermission('administer block types');
      return TRUE;
    }
    return FALSE;
  });
}
else {
          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',
      
$this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;
    parent::__construct($configuration$plugin_id$plugin_definition);

    $this->addCacheTags(['user_list']);
  }

  /** * {@inheritdoc} */
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = AccessResult::allowedIf(!empty($account) && $account->hasPermission('access user profiles'))->cachePerPermissions();
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * {@inheritdoc} */
  public function execute() {
    $results = [];
    if (!$this->isSearchExecutable()) {
      return $results;
    }

    

    public function process(CartDataCollection $data, Cart $original, Cart $toCalculate, SalesChannelContext $context, CartBehavior $behavior): void
    {
        Profiler::trace('cart::promotion::process', function D) use ($data$original$toCalculate$context$behavior): void {
            // always make sure we have             // the line item group builder for our             // line item group rule inside the cart data             $toCalculate->getData()->set(LineItemGroupBuilder::class$this->groupBuilder);

            // if we are in recalculation,             // we must not re-add any promotions. just leave it as it is.             if ($behavior->hasPermission(self::SKIP_PROMOTION)) {
                $items = $original->getLineItems()->filterType(self::LINE_ITEM_TYPE);
                foreach ($items as $item) {
                    $toCalculate->add($item);
                }

                return;
            }

            // if there is no collected promotion we may return - nothing to calculate!             if (!$data->has(self::DATA_KEY)) {
                $lineItemPromotions = $original->getLineItems()->filterType(self::LINE_ITEM_TYPE);
                

  public function testUserSensitiveValidTransitions($from_id$to_id$permission$allowed$result) {
    $user = $this->prophesize(AccountInterface::class);
    // The one listed permission will be returned as instructed; Any others are     // always denied.     $user->hasPermission($permission)->willReturn($allowed);
    $user->hasPermission(Argument::type('string'))->willReturn(FALSE);

    $entity = $this->prophesize(ContentEntityInterface::class);
    $entity = $entity->reveal();
    $entity->moderation_state = new \stdClass();
    $entity->moderation_state->value = $from_id;

    $moderation_info = $this->prophesize(ModerationInformationInterface::class);
    $moderation_info->getWorkflowForEntity($entity)->willReturn($this->workflow);

    $validator = new StateTransitionValidation($moderation_info->reveal());
    
continue;
                }

                $data->set($key$shippingMethods->get($id));
            }
        }, 'cart');
    }

    public function process(CartDataCollection $data, Cart $original, Cart $toCalculate, SalesChannelContext $context, CartBehavior $behavior): void
    {
        Profiler::trace('cart::delivery::process', function D) use ($data$original$toCalculate$context$behavior): void {
            if ($behavior->hasPermission(self::SKIP_DELIVERY_PRICE_RECALCULATION)) {
                $deliveries = $original->getDeliveries();
                $firstDelivery = $deliveries->first();
                if ($firstDelivery === null) {
                    return;
                }

                // Stored original edit shipping cost                 $manualShippingCosts = $toCalculate->getExtension(self::MANUAL_SHIPPING_COSTS) ?? $firstDelivery->getShippingCosts();

                $toCalculate->addExtension(self::MANUAL_SHIPPING_COSTS, $manualShippingCosts);

                
'region' => $region,
        ]);
      }
      if (isset($url)) {
        $build['add_block'] = [
          '#type' => 'link',
          '#url' => $url,
          '#title' => $this->t('Create @entity_type', [
            '@entity_type' => $this->entityTypeManager->getDefinition('block_content')->getSingularLabel(),
          ]),
          '#attributes' => $this->getAjaxAttributes(),
          '#access' => $this->currentUser->hasPermission('create and edit custom blocks'),
        ];
        $build['add_block']['#attributes']['class'][] = 'inline-block-create-button';
      }
    }

    $build['filter'] = [
      '#type' => 'search',
      '#title' => $this->t('Filter by block name'),
      '#title_display' => 'invisible',
      '#size' => 30,
      '#placeholder' => $this->t('Filter by block name'),
      

  public function testHasPermission($permission, array $sessions_with_access, array $sessions_without_access) {
    foreach ($sessions_with_access as $name) {
      $this->assertTrue($this->users[$name]->hasPermission($permission));
    }
    foreach ($sessions_without_access as $name) {
      $this->assertFalse($this->users[$name]->hasPermission($permission));
    }
  }

  /** * Tests the method getRoles exclude or include locked roles based in param. * * @covers ::getRoles * @todo Move roles constants to a class/interface */
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    switch ($operation) {
      case 'view':
        // There is no direct viewing of a menu link, but still for purposes of         // content_translation we need a generic way to check access.         return AccessResult::allowedIfHasPermission($account, 'administer menu');

      case 'update':
        if (!$account->hasPermission('administer menu')) {
          return AccessResult::neutral("The 'administer menu' permission is required.")->cachePerPermissions();
        }
        else {
          // Assume that access is allowed.           $access = AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
          /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
          // If the link is routed determine whether the user has access unless           // they have the 'link to any page' permission.           if (!$account->hasPermission('link to any page') && ($url_object = $entity->getUrlObject()) && $url_object->isRouted()) {
            $link_access = $this->accessManager->checkNamedRoute($url_object->getRouteName()$url_object->getRouteParameters()$account, TRUE);
            $access = $access->andIf($link_access);
          }
$this->assertEquals(1, \Drupal::service('node.grant_storage')->checkAll($this->webUser), 'There is an all realm access record');
    $this->assertTrue(\Drupal::state()->get('node.node_access_needs_rebuild'), 'Node access permissions need to be rebuilt');

    // Rebuild permissions.     $this->drupalGet('admin/reports/status');
    $this->clickLink('Rebuild permissions');
    $this->submitForm([], 'Rebuild permissions');
    $this->assertSession()->pageTextContains('The content access permissions have been rebuilt.');

    // Test if the rebuild by user that cannot bypass node access and does not     // have access to the nodes has been successful.     $this->assertFalse($this->adminUser->hasPermission('bypass node access'));
    $this->assertNull(\Drupal::state()->get('node.node_access_needs_rebuild'), 'Node access permissions have been rebuilt');
    foreach ($nodes as $node) {
      $this->assertTrue($grant_storage->access($node, 'view', $this->webUser)->isAllowed(), 'After rebuilding node access the grant storage returns allowed for the node author.');
      $this->assertFalse($grant_storage->access($node, 'view', $this->adminUser)->isForbidden(), 'After rebuilding node access the grant storage returns forbidden for the admin user.');
    }
    $this->assertEmpty(\Drupal::service('node.grant_storage')->checkAll($this->webUser), 'There is no all realm access record');

    // Test an anonymous node access rebuild from code.     $this->drupalLogout();
    node_access_rebuild();
    foreach ($nodes as $node) {
      

  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    if ($match || $limit) {
      return parent::getReferenceableEntities($match$match_operator$limit);
    }

    $options = [];

    $bundles = $this->entityTypeBundleInfo->getBundleInfo('taxonomy_term');
    $bundle_names = $this->getConfiguration()['target_bundles'] ?: array_keys($bundles);

    $has_admin_access = $this->currentUser->hasPermission('administer taxonomy');
    $unpublished_terms = [];
    foreach ($bundle_names as $bundle) {
      if ($vocabulary = Vocabulary::load($bundle)) {
        /** @var \Drupal\taxonomy\TermInterface[] $terms */
        if ($terms = $this->entityTypeManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) {
          foreach ($terms as $term) {
            if (!$has_admin_access && (!$term->isPublished() || in_array($term->parent->target_id, $unpublished_terms))) {
              $unpublished_terms[] = $term->id();
              continue;
            }
            $options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . Html::escape($this->entityRepository->getTranslationFromContext($term)->label());
          }
Home | Imprint | This part of the site doesn't use cookies.