ServicesMenuResource.php in Services Menu 8
File
src/Plugin/rest/resource/ServicesMenuResource.php
View source
<?php
namespace Drupal\services_menu\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
class ServicesMenuResource extends ResourceBase {
public function get($menu_name = NULL) {
$menu_tree = \Drupal::menuTree();
$generator = \Drupal::urlGenerator();
$tree = $menu_tree
->load($menu_name, new \Drupal\Core\Menu\MenuTreeParameters());
$manipulators = array(
array(
'callable' => 'menu.default_tree_manipulators:checkAccess',
),
array(
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
),
);
$tree = $menu_tree
->transform($tree, $manipulators);
foreach ($tree as $element) {
$link = $element->link;
$path = $generator
->getPathFromRoute($link
->getRouteName());
$menu[$link
->getRouteName()]['title'] = $link
->getTitle();
$menu[$link
->getRouteName()]['url'] = $path;
if ($element->subtree) {
$subtree = $menu_tree
->build($element->subtree);
foreach ($subtree['#items'] as $key => $value) {
$path = $generator
->getPathFromRoute($key);
$menu[$key]['title'] = $value['title'];
$menu[$key]['url'] = $path;
foreach ($subtree['#items'][$key]['below'] as $subkey => $subvalue) {
$path = $generator
->getPathFromRoute($subkey);
$menu[$key]['below'][$subkey]['title'] = $subvalue['title'];
$menu[$key]['below'][$subkey]['url'] = $path;
}
}
}
}
$response = new ResourceResponse($menu);
$response
->addCacheableDependency($menu);
return $response;
}
}