createAccess example



    $operations_access = !empty($pending_term_ids) || $vocabulary_hierarchy === VocabularyInterface::HIERARCHY_MULTIPLE;
    if ($operations_access) {
      $form['help']['#attributes']['class'] = ['messages', 'messages--warning'];
    }

    $errors = $form_state->getErrors();
    $row_position = 0;
    // Build the actual form.     $access_control_handler = $this->entityTypeManager->getAccessControlHandler('taxonomy_term');
    $create_access = $access_control_handler->createAccess($taxonomy_vocabulary->id(), NULL, [], TRUE);
    if ($create_access->isAllowed()) {
      $empty = $this->t('No terms available. <a href=":link">Add term</a>.', [':link' => Url::fromRoute('entity.taxonomy_term.add_form', ['taxonomy_vocabulary' => $taxonomy_vocabulary->id()])->toString()]);
    }
    else {
      $empty = $this->t('No terms available.');
    }
    $form['terms'] = [
      '#type' => 'table',
      '#empty' => $empty,
      '#header' => [
        'term' => $this->t('Name'),
        

  protected function buildActionLinks($vid, TermInterface $forum_term = NULL) {
    $user = $this->currentUser();

    $links = [];
    // Loop through all bundles for forum taxonomy vocabulary field.     foreach ($this->fieldMap['node']['taxonomy_forums']['bundles'] as $type) {
      if ($this->nodeAccess->createAccess($type)) {
        $node_type = $this->nodeTypeStorage->load($type);
        $links[$type] = [
          '#theme' => 'menu_local_action',
          '#link' => [
            'title' => $this->t('Add new @node_type', [
              '@node_type' => $this->nodeTypeStorage->load($type)->label(),
            ]),
            'url' => Url::fromRoute('node.add', ['node_type' => $type]),
          ],
          '#cache' => [
            'tags' => $node_type->getCacheTags(),
          ],


  /** * @covers ::checkAccess * @covers ::checkCreateAccess */
  public function testHandler() {
    $entity = ContentModerationState::create([]);
    $this->assertFalse($this->accessControlHandler->access($entity, 'view'));
    $this->assertFalse($this->accessControlHandler->access($entity, 'update'));
    $this->assertFalse($this->accessControlHandler->access($entity, 'delete'));
    $this->assertFalse($this->accessControlHandler->createAccess());
  }

}
$message->setCopySender(TRUE);

    $this->assertEquals('welcome_message', $message->getMessage());
    $this->assertEquals('sender_name', $message->getSenderName());
    $this->assertEquals('sender_mail', $message->getSenderMail());
    $this->assertTrue($message->copySender());

    $no_access_user = $this->createUser([], NULL, FALSE, ['uid' => 2]);
    $access_user = $this->createUser(['access site-wide contact form'], NULL, FALSE, ['uid' => 3]);
    $admin = $this->createUser(['administer contact forms'], NULL, FALSE, ['uid' => 4]);

    $this->assertFalse(\Drupal::entityTypeManager()->getAccessControlHandler('contact_message')->createAccess(NULL, $no_access_user));
    $this->assertTrue(\Drupal::entityTypeManager()->getAccessControlHandler('contact_message')->createAccess(NULL, $access_user));
    $this->assertTrue($message->access('update', $admin));
    $this->assertFalse($message->access('update', $access_user));
  }

}

  public function access(AccountInterface $account, NodeInterface $node_preview) {
    if ($node_preview->isNew()) {
      $access_controller = $this->entityTypeManager->getAccessControlHandler('node');
      return $access_controller->createAccess($node_preview->bundle()$account[], TRUE);
    }
    else {
      return $node_preview->access('update', $account, TRUE);
    }
  }

}
    // {name}, loop over the raw variables and attempt to replace them in the     // bundle name. If a placeholder does not exist, it won't get replaced.     if ($bundle && str_contains($bundle, '{')) {
      foreach ($route_match->getRawParameters()->all() as $name => $value) {
        $bundle = str_replace('{' . $name . '}', $value$bundle);
      }
      // If we were unable to replace all placeholders, deny access.       if (str_contains($bundle, '{')) {
        return AccessResult::neutral(sprintf("Could not find '%s' request argument, therefore cannot check create access.", $bundle));
      }
    }
    return $this->entityTypeManager->getAccessControlHandler($entity_type)->createAccess($bundle$account[], TRUE);
  }

}

  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    $entity_type_id = $route->getRequirement($this->requirementsKey);
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
    $access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);

    // In case there is no "bundle" entity key, check create access with no     // bundle specified.     if (!$entity_type->hasKey('bundle')) {
      return $access_control_handler->createAccess(NULL, $account[], TRUE);
    }

    $access = AccessResult::neutral();
    $bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($entity_type_id));

    // Include list cache tag as access might change if more bundles are added.     if ($entity_type->getBundleEntityType()) {
      $access->addCacheTags($this->entityTypeManager->getDefinition($entity_type->getBundleEntityType())->getListCacheTags());

      if (empty($route->getOption('_ignore_create_bundle_access'))) {
        // Check if the user is allowed to create new bundles. If so, allow

  public function assertNodeCreateAccess(string $bundle, bool $result, AccountInterface $account, ?string $langcode = NULL) {
    $this->assertEquals($result$this->accessHandler->createAccess($bundle$account[
      'langcode' => $langcode,
    ])$this->nodeAccessAssertMessage('create', $result$langcode));
  }

  /** * Constructs an assert message to display which node access was tested. * * @param string $operation * The operation to check access for. * @param bool $result * Whether access should be granted or not. * @param string|null $langcode * (optional) The language code indicating which translation of the node * to check. If NULL, the untranslated (fallback) access is checked. * * @return string * An assert message string which contains information in plain English * about the node access permission test that was performed. */

  public function add(Request $request) {
    // @todo deprecate see https://www.drupal.org/project/drupal/issues/3346394.     $types = [];
    // Only use block types the user has access to.     foreach ($this->blockContentTypeStorage->loadMultiple() as $type) {
      $access = $this->entityTypeManager()->getAccessControlHandler('block_content')->createAccess($type->id(), NULL, [], TRUE);
      if ($access->isAllowed()) {
        $types[$type->id()] = $type;
      }
    }
    uasort($types[$this->blockContentTypeStorage->getEntityType()->getClass(), 'sort']);
    if ($types && count($types) == 1) {
      $type = reset($types);
      return $this->addForm($type$request);
    }
    if (count($types) === 0) {
      return [
        
public static function checkFileUploadAccess(AccountInterface $account, FieldDefinitionInterface $field_definition, EntityInterface $entity = NULL) {
    assert(is_null($entity) ||
      $field_definition->getTargetEntityTypeId() === $entity->getEntityTypeId() &&
      // Base fields do not have target bundles.       (is_null($field_definition->getTargetBundle()) || $field_definition->getTargetBundle() === $entity->bundle())
    );
    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_access_control_handler = $entity_type_manager->getAccessControlHandler($field_definition->getTargetEntityTypeId());
    $bundle = $entity_type_manager->getDefinition($field_definition->getTargetEntityTypeId())->hasKey('bundle') ? $field_definition->getTargetBundle() : NULL;
    $entity_access_result = $entity
      ? $entity_access_control_handler->access($entity, 'update', $account, TRUE)
      : $entity_access_control_handler->createAccess($bundle$account[], TRUE);
    $field_access_result = $entity_access_control_handler->fieldAccess('edit', $field_definition, NULL, NULL, TRUE);
    return $entity_access_result->andIf($field_access_result);
  }

  /** * Streams file upload data to temporary file and moves to file destination. * * @return string * The temp file path. * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * Thrown when input data cannot be read, the temporary file cannot be * opened, or the temporary file cannot be written. */

  protected function buildMediaTypeAddForm(MediaLibraryState $state) {
    $selected_type_id = $state->getSelectedTypeId();

    $access_handler = $this->entityTypeManager->getAccessControlHandler('media');
    $context = [
      'media_library_state' => $state,
    ];
    if (!$access_handler->createAccess($selected_type_id, NULL, $context)) {
      return [];
    }

    $selected_type = $this->entityTypeManager->getStorage('media_type')->load($selected_type_id);
    $plugin_definition = $selected_type->getSource()->getPluginDefinition();

    if (empty($plugin_definition['forms']['media_library_add'])) {
      return [];
    }

    // After the form to add new media is submitted, we need to rebuild the
return TRUE;
    });
  }

  /** * {@inheritdoc} */
  public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
    if ($operation == 'create') {
      return $this->entityTypeManager()
        ->getAccessControlHandler($this->entityTypeId)
        ->createAccess($this->bundle()$account[]$return_as_object);
    }
    return $this->entityTypeManager()
      ->getAccessControlHandler($this->entityTypeId)
      ->access($this$operation$account$return_as_object);
  }

  /** * {@inheritdoc} */
  public function language() {
    if ($key = $this->getEntityType()->getKey('langcode')) {
      


    if ($entity->access('access taxonomy overview')) {
      $operations['list'] = [
        'title' => t('List terms'),
        'weight' => 0,
        'url' => $entity->toUrl('overview-form'),
      ];
    }

    $taxonomy_term_access_control_handler = $this->entityTypeManager->getAccessControlHandler('taxonomy_term');
    if ($taxonomy_term_access_control_handler->createAccess($entity->id())) {
      $operations['add'] = [
        'title' => t('Add terms'),
        'weight' => 10,
        'url' => Url::fromRoute('entity.taxonomy_term.add_form', ['taxonomy_vocabulary' => $entity->id()]),
      ];
    }

    return $operations;
  }

  /** * {@inheritdoc} */
$access_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);

    if (!empty($parameters['revision_id'])) {
      $entity = $storage->loadRevision($parameters['revision_id']);
      $entity_access = $access_handler->access($entity, 'update', $account, TRUE);
    }
    elseif ($parameters['entity_id']) {
      $entity = $storage->load($parameters['entity_id']);
      $entity_access = $access_handler->access($entity, 'update', $account, TRUE);
    }
    else {
      $entity_access = $access_handler->createAccess($bundle$account[], TRUE);
    }

    // If entity-level access is denied, there's no point in continuing.     if (!$entity_access->isAllowed()) {
      if ($entity_access instanceof RefinableCacheableDependencyInterface) {
        $entity_access->addCacheableDependency($state);
      }
      return $entity_access;
    }

    // If the entity has not been loaded, create it in memory now.
$entity_values = ($which_entity === 'unlocked')
      ? ['locked' => FALSE]
      : ['locked' => TRUE];
    $entity_values['id'] = $this->randomMachineName();
    $entity = DateFormat::create($entity_values);
    $entity->save();

    static::assertEquals($view_label_access_result$this->accessControlHandler->access($entity, 'view label', $user, TRUE));
    static::assertEquals($view_access_result$this->accessControlHandler->access($entity, 'view', $user, TRUE));
    static::assertEquals($update_access_result$this->accessControlHandler->access($entity, 'update', $user, TRUE));
    static::assertEquals($delete_access_result$this->accessControlHandler->access($entity, 'delete', $user, TRUE));
    static::assertEquals($create_access_result$this->accessControlHandler->createAccess(NULL, $user[], TRUE));
  }

  public function testAccessProvider() {
    $c = new ContainerBuilder();
    $cache_contexts_manager = (new Prophet())->prophesize(CacheContextsManager::class);
    $cache_contexts_manager->assertValidTokens()->willReturn(TRUE);
    $cache_contexts_manager->reveal();
    $c->set('cache_contexts_manager', $cache_contexts_manager);
    \Drupal::setContainer($c);

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