You are here

class CoffeeController in Coffee 8

Provides route responses for coffee.module.

Hierarchy

Expanded class hierarchy of CoffeeController

File

src/Controller/CoffeeController.php, line 20

Namespace

Drupal\coffee\Controller
View source
class CoffeeController extends ControllerBase {

  /**
   * The coffee config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuLinkTree;

  /**
   * The local task manager service.
   *
   * @var \Drupal\Core\Menu\LocalTaskManagerInterface
   */
  protected $localTaskManager;

  /**
   * The access manager service.
   *
   * @var \Drupal\Core\Access\AccessManagerInterface
   */
  protected $accessManager;

  /**
   * The url generator service.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs a new CoffeeController object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\Menu\MenuLinkTreeInterface $menu_link_tree
   *   The menu link tree service.
   * @param \Drupal\Core\Menu\LocalTaskManagerInterface $local_task_manager
   *   The local task manager service.
   * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
   *   The access manager service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MenuLinkTreeInterface $menu_link_tree, LocalTaskManagerInterface $local_task_manager, AccessManagerInterface $access_manager, UrlGeneratorInterface $url_generator, RouteMatchInterface $route_match) {
    $this->config = $config_factory
      ->get('coffee.configuration');
    $this->menuLinkTree = $menu_link_tree;
    $this->localTaskManager = $local_task_manager;
    $this->accessManager = $access_manager;
    $this->urlGenerator = $url_generator;
    $this->routeMatch = $route_match;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('menu.link_tree'), $container
      ->get('plugin.manager.menu.local_task'), $container
      ->get('access_manager'), $container
      ->get('coffee.url_generator'), $container
      ->get('current_route_match'));
  }

  /**
   * Outputs the data that is used for the Coffee autocompletion in JSON.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The json response.
   */
  public function coffeeData() {
    $output = [];
    foreach ($this->config
      ->get('coffee_menus') as $menu_name) {
      $tree = $this
        ->getMenuTreeElements($menu_name);
      $commands_group = $menu_name == 'account' ? ':user' : NULL;
      foreach ($tree as $tree_element) {
        $link = $tree_element->link;
        $output[$link
          ->getRouteName()] = [
          'value' => $link
            ->getUrlObject()
            ->setUrlGenerator($this->urlGenerator)
            ->toString(),
          'label' => $link
            ->getTitle(),
          'command' => $commands_group,
        ];
        $tasks = $this
          ->getLocalTasksForRoute($link
          ->getRouteName(), $link
          ->getRouteParameters());
        foreach ($tasks as $route_name => $task) {
          if (empty($output[$route_name])) {
            $output[$route_name] = [
              'value' => $task['url']
                ->setUrlGenerator($this->urlGenerator)
                ->toString(),
              'label' => $link
                ->getTitle() . ' - ' . $task['title'],
              'command' => NULL,
            ];
          }
        }
      }
    }
    $commands = $this
      ->moduleHandler()
      ->invokeAll('coffee_commands');
    if (!empty($commands)) {
      $output = array_merge($output, $commands);
    }

    // Re-index the array.
    $output = array_values($output);
    return new JsonResponse($output);
  }

  /**
   * Retrieves the menu tree elements for the given menu.
   *
   * Every element returned by this method is already access checked.
   *
   * @param string $menu_name
   *   The menu name.
   *
   * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
   *   A flatten array of menu link tree elements for the given menu.
   */
  protected function getMenuTreeElements($menu_name) {
    $parameters = new MenuTreeParameters();
    $tree = $this->menuLinkTree
      ->load($menu_name, $parameters);
    $manipulators = [
      [
        'callable' => 'menu.default_tree_manipulators:checkNodeAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:checkAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:flatten',
      ],
    ];
    $tree = $this->menuLinkTree
      ->transform($tree, $manipulators);

    // Top-level inaccessible links are *not* removed; it is up
    // to the code doing something with the tree to exclude inaccessible links.
    // @see menu.default_tree_manipulators:checkAccess
    foreach ($tree as $key => $element) {
      if (!$element->access
        ->isAllowed()) {
        unset($tree[$key]);
      }
    }
    return $tree;
  }

  /**
   * Retrieve all the local tasks for a given route.
   *
   * Every element returned by this method is already access checked.
   *
   * @param string $route_name
   *   The route name for which find the local tasks.
   * @param array $route_parameters
   *   The route parameters.
   *
   * @return array
   *   A flatten array that contains the local tasks for the given route.
   *   Each element in the array is keyed by the route name associated with
   *   the local tasks and contains:
   *     - title: the title of the local task.
   *     - url: the url object for the local task.
   *     - localized_options: the localized options for the local task.
   */
  protected function getLocalTasksForRoute($route_name, array $route_parameters) {
    $links = [];
    $tree = $this->localTaskManager
      ->getLocalTasksForRoute($route_name);
    foreach ($tree as $instances) {

      /* @var $instances \Drupal\Core\Menu\LocalTaskInterface[] */
      foreach ($instances as $child) {
        $child_route_name = $child
          ->getRouteName();

        // Merges the parent's route parameter with the child ones since you
        // calculate the local tasks outside of parent route context.
        $child_route_parameters = $child
          ->getRouteParameters($this->routeMatch) + $route_parameters;
        if (strpos($child_route_name, 'config_translate') !== FALSE && $this->accessManager
          ->checkNamedRoute($child_route_name, $child_route_parameters)) {
          $links[$child_route_name] = [
            'title' => $child
              ->getTitle(),
            'url' => Url::fromRoute($child_route_name, $child_route_parameters),
            'localized_options' => $child
              ->getOptions($this->routeMatch),
          ];
        }
      }
    }
    return $links;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CoffeeController::$accessManager protected property The access manager service.
CoffeeController::$config protected property The coffee config.
CoffeeController::$localTaskManager protected property The local task manager service.
CoffeeController::$menuLinkTree protected property The menu link tree service.
CoffeeController::$routeMatch protected property The current route match.
CoffeeController::$urlGenerator protected property The url generator service. Overrides UrlGeneratorTrait::$urlGenerator
CoffeeController::coffeeData public function Outputs the data that is used for the Coffee autocompletion in JSON.
CoffeeController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
CoffeeController::getLocalTasksForRoute protected function Retrieve all the local tasks for a given route.
CoffeeController::getMenuTreeElements protected function Retrieves the menu tree elements for the given menu.
CoffeeController::__construct public function Constructs a new CoffeeController object.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.