You are here

public function DrupalOrg::buildLink in Freelinking 8.3

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

File

src/Plugin/freelinking/DrupalOrg.php, line 104

Class

DrupalOrg
Freelinking drupal.org and drupal.org project plugin.

Namespace

Drupal\freelinking\Plugin\freelinking

Code

public function buildLink(array $target) {
  $scrape = $this
    ->getConfiguration()['settings']['scrape'];
  $path = preg_match('/o(rg)?$/', $target['indicator']) ? 'node' : 'project';
  $url = 'https://drupal.org/' . $path . '/' . $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('Drupal.org: “@title”', [
          '@title' => $page_title,
        ]);
      }
      else {
        $prefix = is_numeric($target['dest']) ? '#' : '';
        $link['#title'] = $prefix . $target['dest'];
      }
    } 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'] : ucwords($path) . ' ' . $target['dest'];
  }
  return $link;
}