function LinksetController::process

Same name in other branches
  1. 11.x core/modules/system/src/Controller/LinksetController.php \Drupal\system\Controller\LinksetController::process()

Serve linkset requests.

Parameters

\Symfony\Component\HttpFoundation\Request $request: An HTTP request.

\Drupal\system\MenuInterface $menu: A menu for which to produce a linkset.

Return value

\Drupal\Core\Cache\CacheableJsonResponse A linkset response.

File

core/modules/system/src/Controller/LinksetController.php, line 54

Class

LinksetController
Linkset controller.

Namespace

Drupal\system\Controller

Code

public function process(Request $request, MenuInterface $menu) {
    // Load the given menu's tree of elements.
    $tree = $this->loadMenuTree($menu);
    // Get the incoming request URI and parse it so the linkset can use a
    // relative URL for the linkset anchor.
    [
        'path' => $path,
        'query' => $query,
    ] = parse_url($request->getUri()) + [
        'query' => FALSE,
    ];
    // Construct a relative URL.
    $anchor = $path . (!empty($query) ? '?' . $query : '');
    $cacheability = CacheableMetadata::createFromObject($menu);
    // Encode the menu tree as links in the application/linkset+json media type
    // and add the machine name of the menu to which they belong.
    $menu_id = $menu->id();
    $links = $this->toLinkTargetObjects($tree, $cacheability);
    foreach ($links as $rel => $target_objects) {
        $links[$rel] = array_map(function (array $target) use ($menu_id) {
            // According to the Linkset specification, this member must be an array
            // since the "machine-name" target attribute is non-standard.
            // See https://tools.ietf.org/html/draft-ietf-httpapi-linkset-08#section-4.2.4.3
            return $target + [
                'machine-name' => [
                    $menu_id,
                ],
            ];
        }, $target_objects);
    }
    $linkset = !empty($tree) ? [
        [
            'anchor' => $anchor,
        ] + $links,
    ] : [];
    $data = [
        'linkset' => $linkset,
    ];
    // Set the response content-type header.
    $headers = [
        'content-type' => 'application/linkset+json',
    ];
    $response = new CacheableJsonResponse($data, 200, $headers);
    // Attach cacheability metadata to the response.
    $response->addCacheableDependency($cacheability);
    return $response;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.