You are here

public function AuthenticationLinkProvider::getLink in JSON:API Hypermedia 8

Adds, alters or removes hyperlinks from a link collection.

Parameters

\Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel|\Drupal\jsonapi\JsonApiResource\ResourceObject|\Drupal\jsonapi\JsonApiResource\Relationship $context: The context object from which links should be generated.

Return value

\Drupal\jsonapi_hypermedia\AccessRestrictedLink A link to be added to the context object. An AccessRestrictedLink should be returned if the link target may be inaccessible to some users.

Overrides LinkProviderInterface::getLink

File

examples/Plugin/jsonapi_hypermedia/LinkProvider/AuthenticationLinkProvider.php, line 67

Class

AuthenticationLinkProvider
Adds an `authenticate` link for unauthenticated requests.

Namespace

Drupal\jsonapi_hypermedia\Plugin\jsonapi_hypermedia\LinkProvider

Code

public function getLink($context) {
  assert($context instanceof JsonApiDocumentTopLevel);
  $is_authenticated = $this->currentUser
    ->isAuthenticated();
  $route_name = !$is_authenticated ? 'user.login.http' : 'user.logout.http';
  $login_url = Url::fromUri($route_name, [
    'query' => [
      '_format' => 'json',
    ],
  ]);
  $link_cacheability = new CacheableMetadata();
  $link_cacheability
    ->addCacheContexts([
    'session.exists',
    'user.roles:anonymous',
  ]);

  // The link is always accessible, but the link location and link relation
  // type depend on the request. This example also uses the link's target
  // attributes to indicate the media type of the link target, since it is not
  // `application/vnd.api+json` as might be expected.
  return AccessRestrictedLink::createLink(AccessResult::allowed(), $link_cacheability, $login_url, $this
    ->getLinkRelationType(), [
    'type' => 'application/json',
  ]);
}