You are here

public function External::buildLink in Freelinking 8.3

Same name and namespace in other branches
  1. 4.0.x src/Plugin/freelinking/External.php \Drupal\freelinking\Plugin\freelinking\External::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

1 method overrides External::buildLink()
DrupalOrg::buildLink in src/Plugin/freelinking/DrupalOrg.php
Build a link with the plugin.

File

src/Plugin/freelinking/External.php, line 97

Class

External
Freelinking external link plugin.

Namespace

Drupal\freelinking\Plugin\freelinking

Code

public function buildLink(array $target) {
  $scrape = $this
    ->getConfiguration()['settings']['scrape'];
  $scheme = preg_match('/^http(s)?$/', $target['indicator']) === 1 ? $target['indicator'] . ':' : '';
  $url = $scheme . $target['dest'];
  $link = [
    '#type' => 'link',
    '#url' => Url::fromUri($url, [
      'absolute' => TRUE,
      'language' => $target['language'],
    ]),
    '#attributes' => [
      'title' => isset($target['tooltip']) ? $target['tooltip'] : $this
        ->getTip(),
    ],
  ];

  // Get the page title from the external URL or use the target text.
  if (!$target['text'] && $scrape) {
    try {
      $page_title = $this
        ->getPageTitle($url);
      if ($page_title) {
        $link['#title'] = $this
          ->t('Ext. link: “@title”', [
          '@title' => $page_title,
        ]);
      }
      else {
        $link['#title'] = $url;
      }
    } catch (RequestException $e) {
      $link = [
        '#theme' => 'freelink_error',
        '#plugin' => 'external',
      ];
      if ($e
        ->getResponse()
        ->getStatusCode() >= 400) {
        $link['#message'] = $this
          ->t('External target “@url” not found', [
          '@url' => $url,
        ]);
      }
    }
  }
  else {
    $link['#title'] = $target['text'] ? $target['text'] : $target['dest'];
  }
  return $link;
}