public function RestMenuItemsResource::get in Rest menu items 8.2
Same name and namespace in other branches
- 8 src/Plugin/rest/resource/RestMenuItemsResource.php \Drupal\rest_menu_items\Plugin\rest\resource\RestMenuItemsResource::get()
- 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.
Parameters
string|null $menu_name: The menu name.
Return value
\Drupal\rest\ResourceResponse The response containing a list of bundle names.
Throws
\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
\Drupal\Component\Plugin\Exception\PluginNotFoundException
File
- src/
Plugin/ rest/ resource/ RestMenuItemsResource.php, line 106
Class
- RestMenuItemsResource
- Provides a resource to get bundles by entity.
Namespace
Drupal\rest_menu_items\Plugin\rest\resourceCode
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)) {
$response = new ResourceResponse($tree);
if ($response instanceof CacheableResponseInterface) {
$response
->addCacheableDependency(new RestMenuItemsCacheableDependency($menu_name, $this->minDepth, $this->maxDepth));
}
return $response;
}
// 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);
// Return if the menu has no entries.
if (empty($menu['#items'])) {
return new ResourceResponse([]);
}
$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 RestMenuItemsCacheableDependency($menu_name, $this->minDepth, $this->maxDepth));
}
// Return the JSON response.
return $response;
}
throw new HttpException($this
->t("Menu name was not provided"));
}