route_ui-1.0.0-alpha2/src/Controller/AutocompleteController.php

src/Controller/AutocompleteController.php
<?php

namespace Drupal\route_ui\Controller;

use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\PrivateKey;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Site\Settings;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Autocomplete controller for route names.
 */
class AutocompleteController extends ControllerBase {

  /**
   * The route provider.
   *
   * @var \Drupal\Core\Routing\RouteProviderInterface
   */
  protected $routeProvider;

  /**
   * The private key.
   *
   * @var \Drupal\Core\PrivateKey
   */
  protected $privateKey;

  /**
   * AutocompleteController constructor.
   *
   * @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
   *   The route provider.
   * @param \Drupal\Core\PrivateKey $private_key
   *   The private key.
   */
  public function __construct(RouteProviderInterface $route_provider, PrivateKey $private_key) {
    $this->routeProvider = $route_provider;
    $this->privateKey = $private_key;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new static(
      $container->get('router.route_provider'),
      $container->get('private_key')
    );
  }

  /**
   * Returns a list of routes that start with the provided string.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   * @param string $user_token
   *   A token based on the current user.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The list of route names.
   */
  public function handleAutocomplete(Request $request, string $user_token): JsonResponse {
    $current_token = Crypt::hmacBase64($this->currentUser()->id(), Settings::getHashSalt() . $this->privateKey->get());
    if (!hash_equals($user_token, $current_token) || $this->currentUser()->isAnonymous()) {
      throw new AccessDeniedHttpException();
    }

    $results = [];
    $input = $request->query->get('q');

    if (!$input) {
      return new JsonResponse($results);
    }

    $input = Xss::filter($input);

    foreach ($this->routeProvider->getAllRoutes() as $route_name => $route) {
      if (strpos($route_name, $input) !== 0) {
        continue;
      }
      $results[] = [
        'value' => $route_name,
        'label' => $route_name,
      ];
    }

    return new JsonResponse($results);
  }

}

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

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