You are here

public function User::buildLink in Freelinking 8.3

Same name and namespace in other branches
  1. 4.0.x src/Plugin/freelinking/User.php \Drupal\freelinking\Plugin\freelinking\User::buildLink()

Build a link with the plugin.

Parameters

array $target: The target array with including the following keys:

  • text: The text to display in the URL.
  • indicator: The indicator string.
  • dest: The destination string for the plugin to turn into a URI.
  • tooltip: An optional tooltip.
  • language: A language object.

Return value

array Link array.

Overrides FreelinkingPluginInterface::buildLink

File

src/Plugin/freelinking/User.php, line 77

Class

User
Freelinking user plugin.

Namespace

Drupal\freelinking\Plugin\freelinking

Code

public function buildLink(array $target) {
  if ($this->currentUser
    ->hasPermission('access user profiles')) {
    $account = NULL;

    // Finds user account by user identifier (uid) or user name.
    if (is_numeric($target['dest'])) {
      $account = $this->entityTypeManager
        ->getStorage('user')
        ->load($target['dest']);
    }
    else {

      /** @var \Drupal\user\UserInterface[] $accounts */
      $accounts = $this->entityTypeManager
        ->getStorage('user')
        ->loadByProperties([
        'name' => $target['dest'],
      ]);
      if (count($accounts) === 1) {
        $account = array_shift($accounts);
      }
    }
    if (NULL !== $account) {
      $link = [
        '#type' => 'link',
        '#title' => isset($target['text']) ? $target['text'] : $account
          ->getDisplayName(),
        '#url' => Url::fromRoute('entity.user.canonical', [
          'user' => $account
            ->id(),
        ], [
          'language' => $target['language'],
        ]),
        '#attributes' => [
          'title' => isset($target['tooltip']) ? $target['tooltip'] : $this
            ->getTip(),
        ],
      ];
    }
    else {
      $link = [
        '#theme' => 'freelink_error',
        '#plugin' => 'user',
        '#message' => $this
          ->t('User %user not found', [
          '%user' => $target['dest'],
        ]),
      ];
    }
  }
  else {
    $link = [
      '#theme' => 'freelink_error',
      '#plugin' => 'user',
      '#message' => $this
        ->t('Unauthorized to view user profile.'),
    ];
  }
  return $link;
}