toolbar_plus-1.0.x-dev/src/EventSubscriber/ShouldNotEditMode.php

src/EventSubscriber/ShouldNotEditMode.php
<?php

declare(strict_types=1);

namespace Drupal\toolbar_plus\EventSubscriber;

use Drupal\Core\Routing\AdminContext;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\toolbar_plus\Event\ShouldNotEditModeEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Should not edit.
 */
final class ShouldNotEditMode implements EventSubscriberInterface {

  private array $ignoredRoutes = [
    'node.add',
    'entity.node.edit_form',
  ];

  public function __construct(
    private readonly AdminContext $routerAdminContext,
    private readonly RouteMatchInterface $routeMatch,
    private readonly AccountProxyInterface $currentUser,
    private readonly PathMatcherInterface $pathMatcher,
  ) {}

  /**
   * Kernel request event handler.
   */
  public function onShouldNotEditMode(ShouldNotEditModeEvent $event): void {
    // User doesn't have edit mode access.
    if (!$this->currentUser->hasPermission('use toolbar plus edit mode')) {
      $event->setShouldNotEdit();
      return;
    }
    $route_match = $this->routeMatch->getCurrentRouteMatch();
    if (in_array($route_match->getRouteName(), $this->ignoredRoutes, TRUE)) {
      $event->setShouldNotEdit();
      return;
    }

    // Don't edit admin pages.
    $route = $route_match->getRouteObject();
    if ($this->routerAdminContext->isAdminRoute($route)) {
      $event->setShouldNotEdit();
      return;
    }
    // Don't edit the home page. If we want to support home page editing we need
    // to revisit the editMode cookie as that would set editMode=enabled; path=/
    // which would be available on all routes.
    if ($this->pathMatcher->isFrontPage()) {
      $event->setShouldNotEdit();
      return;
    }

    // Ensure that we only have one entity parameter in the route.
    $parameters = $this->routeMatch->getParameters()->all();
    $top_level_entity = NULL;
    foreach ($parameters as $entity) {
      if ($entity instanceof EntityInterface) {
        if (is_null($top_level_entity)) {
          $top_level_entity = $entity;
        } else {
          // If there is more than one it's not obvious which one is the parent,
          // so we should probably not try to edit.
          $event->setShouldNotEdit();
          return;
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      ShouldNotEditModeEvent::class => ['onShouldNotEditMode'],
    ];
  }

}

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

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