You are here

public function MenuItemsResource::process in JSON:API Menu Items 1.1.x

Same name and namespace in other branches
  1. 1.2.x src/Resource/MenuItemsResource.php \Drupal\jsonapi_menu_items\Resource\MenuItemsResource::process()
  2. 1.0.x src/Resource/MenuItemsResource.php \Drupal\jsonapi_menu_items\Resource\MenuItemsResource::process()

Process the resource request.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request.

\Drupal\system\MenuInterface $menu: The menu.

Return value

\Drupal\jsonapi\ResourceResponse The response.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/Resource/MenuItemsResource.php, line 46

Class

MenuItemsResource
Processes a request for a collection of featured nodes.

Namespace

Drupal\jsonapi_menu_items\Resource

Code

public function process(Request $request, MenuInterface $menu) : ResourceResponse {
  $cacheability = new CacheableMetadata();
  $cacheability
    ->addCacheableDependency($menu);
  $parameters = new MenuTreeParameters();
  $parameters
    ->onlyEnabledLinks();
  $parameters
    ->setMinDepth(0);
  $menu_tree = \Drupal::menuTree();
  $tree = $menu_tree
    ->load($menu
    ->id(), $parameters);
  if (empty($tree)) {
    $response = $this
      ->createJsonapiResponse(new ResourceObjectData([]), $request, 403, []);
    $response
      ->addCacheableDependency($cacheability);
    return $response;
  }
  $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);
  $this
    ->getMenuItems($tree, $this->menuItems, $cacheability);
  $data = new ResourceObjectData($this->menuItems);
  $response = $this
    ->createJsonapiResponse($data, $request, 200, []);
  $response
    ->addCacheableDependency($cacheability);
  return $response;
}