grant-1.x-dev/src/Plugin/views/access/GrantRole.php

src/Plugin/views/access/GrantRole.php
<?php

namespace Drupal\grant\Plugin\views\access;

use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\grant\GrantMain;
use Drupal\user\RoleInterface;
use Drupal\user\RoleStorageInterface;
use Drupal\views\Plugin\views\access\AccessPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;

/**
 * Access plugin that provides grant context role-based access control.
 *
 * @ingroup views_access_plugins
 *
 * @ViewsAccess(
 *   id = "grant_role",
 *   title = @Translation("Grant Context Role"),
 *   help = @Translation("Access will be allowed to users with any of the specified roles globally or via grant assign.")
 * )
 */
class GrantRole extends AccessPluginBase implements CacheableDependencyInterface {

  /**
   * {@inheritdoc}
   */
  protected $usesOptions = TRUE;

  /**
   * The role storage.
   *
   * @var \Drupal\user\RoleStorageInterface
   */
  protected $roleStorage;

  /**
   * The grant main service.
   *
   * @var \Drupal\grant\GrantMain
   */
  protected $grantMain;

  /**
   * Constructs a Role object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\user\RoleStorageInterface $role_storage
   *   The role storage.
   * @param \Drupal\grant\GrantMain $grant_main
   *   The grant main service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RoleStorageInterface $role_storage, GrantMain $grant_main) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->roleStorage = $role_storage;
    $this->grantMain = $grant_main;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')->getStorage('user_role'),
      $container->get('grant.main'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function access(AccountInterface $account) {
    $access = $this->grantMain->userAssignedGrantHasAccessPathCurrent($this->options, $account);
    return $access;
  }

  /**
   * {@inheritdoc}
   */
  public function alterRouteDefinition(Route $route) {
    $route->setRequirement('_grant_access_check', $this->grantMain->createGrantAccessCheckString($this->options));
  }

  /**
   * {@inheritdoc}
   */
  public function summaryTitle() {
    return $this->grantMain->createGrantAccessCheckString($this->options);
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['grant_role'] = ['default' => []];
    $options['e_type'] = ['default' => '_none'];
    $options['e_type_arg'] = ['default' => 1];
    $options['e_id_type'] = ['default' => 'uuid'];
    $options['e_id_arg'] = ['default' => 2];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $path_options = [1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6];
    $e_value_type_options = ['uuid' => 'UUID', 'serial' => 'serial ID'];
    $form['grant_role'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Role'),
      '#default_value' => $this->options['grant_role'],
      '#options' => array_map(fn(RoleInterface $role) => Html::escape($role->label()), $this->roleStorage->loadMultiple()),
      '#description' => $this->t('Only the checked roles will be able to access this display.'),
    ];
    $form['e_type'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Entity type: machine name.'),
      '#default_value' => $this->options['e_type'],
      '#description' => $this->t('Use this string e.g. "node" for a "hard" coded config or the path section below.'),
    ];
    $form['e_type_arg'] = [
      '#type' => 'select',
      '#options' => $path_options,
      '#title' => $this->t('Entity type: path segment'),
      '#default_value' => $this->options['e_type_arg'],
      '#description' => $this->t('Will be ignored if machine name above is not empty.'),
    ];
    $form['e_id_type'] = [
      '#type' => 'select',
      '#options' => $e_value_type_options,
      '#title' => $this->t('Entity ID: type'),
      '#default_value' => $this->options['e_id_type'],
      '#description' => $this->t('Select if entity id to check is UUID or serial ID like "nid".'),
      '#disabled' => FALSE,
    ];
    $form['e_id_arg'] = [
      '#type' => 'select',
      '#options' => $path_options,
      '#title' => $this->t('Entity ID: path segment'),
      '#default_value' => $this->options['e_id_arg'],
      '#description' => $this->t('In which path segment contains the uuid or serial id of the entoty to check.'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    $role = $form_state->getValue(['access_options', 'grant_role']);
    $role = array_filter($role);

    if (!$role) {
      $form_state->setError($form['grant_role'], $this->t('You must select at least one role if type is "by role"'));
    }

    $form_state->setValue(['access_options', 'grant_role'], $role);
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

    foreach (array_keys($this->options['grant_role']) as $rid) {
      if ($role = $this->roleStorage->load($rid)) {
        $dependencies[$role->getConfigDependencyKey()][] = $role->getConfigDependencyName();
      }
    }

    return $dependencies;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    // @todo add grant cache contexts
    // return ['user.roles'];
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // @todo add grant cache tags
    return [];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc