You are here

public function RestMenuItemsResource::get in Rest menu items 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/rest/resource/RestMenuItemsResource.php \Drupal\rest_menu_items\Plugin\rest\resource\RestMenuItemsResource::get()
  2. 3.0.x src/Plugin/rest/resource/RestMenuItemsResource.php \Drupal\rest_menu_items\Plugin\rest\resource\RestMenuItemsResource::get()

Responds to GET requests.

Returns a list of menu items for specified menu name.

Return value

\Drupal\rest\ResourceResponse The response containing a list of bundle names.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException A HTTP Exception.

File

src/Plugin/rest/resource/RestMenuItemsResource.php, line 134
Create the menu item REST resource.

Class

RestMenuItemsResource
Provides a resource to get bundles by entity.

Namespace

Drupal\rest_menu_items\Plugin\rest\resource

Code

public function get($menu_name = NULL) {
  if ($menu_name) {

    // Setup variables.
    $this
      ->setup();

    // Create the parameters.
    $parameters = new MenuTreeParameters();
    $parameters
      ->onlyEnabledLinks();
    if (!empty($this->maxDepth)) {
      $parameters
        ->setMaxDepth($this->maxDepth);
    }
    if (!empty($this->minDepth)) {
      $parameters
        ->setMinDepth($this->minDepth);
    }

    // Load the tree based on this set of parameters.
    $menu_tree = \Drupal::menuTree();
    $tree = $menu_tree
      ->load($menu_name, $parameters);

    // Return if the menu does not exist or has no entries
    if (empty($tree)) {
      return new ResourceResponse($tree);
    }

    // Transform the tree using the manipulators you want.
    $manipulators = [
      // Only show links that are accessible for the current user.
      [
        'callable' => 'menu.default_tree_manipulators:checkAccess',
      ],
      // Use the default sorting of menu links.
      [
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ],
    ];
    $tree = $menu_tree
      ->transform($tree, $manipulators);

    // Finally, build a renderable array from the transformed tree.
    $menu = $menu_tree
      ->build($tree);
    $this
      ->getMenuItems($menu['#items'], $this->menuItems);

    // Return response
    $response = new ResourceResponse(array_values($this->menuItems));

    // Configure caching for minDepth and maxDepth parameters
    if ($response instanceof CacheableResponseInterface) {
      $response
        ->addCacheableDependency(new RestMenuItemsCachableDepenency($menu_name, $this->minDepth, $this->maxDepth));
    }
    return $response;
  }
  throw new HttpException(t("Menu name was not provided"));
}