block_editor-1.0.x-dev/src/Access/BlockEditorFormAccessCheck.php

src/Access/BlockEditorFormAccessCheck.php
<?php

namespace Drupal\block_editor\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\block_editor\Service\EntityManager;
use Symfony\Component\Routing\Route;

/**
 * Controls access to Block Editor content entity edit routes.
 */
class BlockEditorFormAccessCheck implements AccessInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * The Block Editor entity manager.
   *
   * @var \Drupal\block_editor\Service\EntityManager
   */
  protected EntityManager $entityManager;

  /**
   * Constructs a new BlockEditorFormAccessCheck.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityManager $entity_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function access(Route $route, RouteMatchInterface $route_match) {
    $entity = $this->extractContentEntity($route_match);

    if (!$entity) {
      return AccessResult::forbidden();
    }

    $bundle_entity = $this->loadBundleEntity($entity);
    if ($bundle_entity && $this->entityManager->isBlockEditorEnabledForEntity($bundle_entity)) {
      return AccessResult::allowed()->addCacheableDependency($bundle_entity);
    }

    return AccessResult::forbidden();
  }

  /**
   * Extracts the first content entity from the route parameters.
   */
  protected function extractContentEntity(RouteMatchInterface $route_match): ?ContentEntityInterface {
    foreach ($route_match->getParameters() as $parameter) {
      if ($parameter instanceof ContentEntityInterface) {
        return $parameter;
      }
    }

    return NULL;
  }

  /**
   * Loads the bundle config entity for a content entity.
   */
  protected function loadBundleEntity(ContentEntityInterface $entity): ?object {
    $entity_type = $entity->getEntityType();
    $bundle_entity_type_id = $entity_type->getBundleEntityType();

    if (!$bundle_entity_type_id) {
      return NULL;
    }

    $bundle_storage = $this->entityTypeManager->getStorage($bundle_entity_type_id);
    return $bundle_storage->load($entity->bundle());
  }

}

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

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