You are here

public function UserLinkApiToken::build in API Tokens 8.2

Same name and namespace in other branches
  1. 8 api_tokens_example/src/Plugin/ApiToken/UserLinkApiToken.php \Drupal\api_tokens_example\Plugin\ApiToken\UserLinkApiToken::build()

Build callback.

Parameters

int $id: (optional) The user ID.

return array A renderable array.

See also

\Drupal\api_tokens\ApiTokenPluginInterface::build();

File

api_tokens_example/src/Plugin/ApiToken/UserLinkApiToken.php, line 57

Class

UserLinkApiToken
Provides a User Link API token.

Namespace

Drupal\api_tokens_example\Plugin\ApiToken

Code

public function build($id = NULL) {
  $build = [];
  if ($id) {
    $user = User::load($id);
    if ($user && $user
      ->access('view')) {
      $build = [
        '#markup' => $user
          ->toLink()
          ->toString(),
      ];
      $this
        ->addCacheContexts([
        'user',
      ]);
      $this
        ->addCacheableDependency($user);
    }
  }
  else {
    $build = Link::createFromRoute(\Drupal::currentUser()
      ->getDisplayName(), 'user.page')
      ->toRenderable();
    $this
      ->addCacheContexts([
      'user',
    ]);
  }
  return $build;
}