You are here

public function File::buildLink in Freelinking 8.3

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

Class

File
Freelinking file plugin.

Namespace

Drupal\freelinking\Plugin\freelinking

Code

public function buildLink(array $target) {
  $scheme = $this
    ->getConfiguration()['settings']['scheme'];

  // Remove slash if it's present at first character.
  $dest = preg_replace('/^\\//', '', $target['dest']);
  $path = $scheme . '://' . $dest;
  $stream_wrapper = $this
    ->loadScheme($scheme);
  $stream_wrapper
    ->setUri($path);

  // Make sure that the file exists on the given scheme.
  if (!$stream_wrapper
    ->realpath()) {
    return [
      '#theme' => 'freelink_error',
      '#plugin' => 'file',
      '#message' => $this
        ->t('File @name not found', [
        '@name' => basename($path),
      ]),
    ];
  }

  // Check file access.
  $headers = $this->moduleHandler
    ->invokeAll('file_download', [
    $path,
  ]);
  if (in_array(-1, $headers)) {
    return [
      '#theme' => 'freelink_error',
      '#plugin' => 'file',
      '#message' => $this
        ->t('File @name not found', [
        '@name' => basename($path),
      ]),
    ];
  }

  // Return a link to the file.
  $file_url = $stream_wrapper
    ->getExternalUrl();
  return [
    '#type' => 'link',
    '#title' => isset($target['text']) ? $target['text'] : basename($path),
    '#url' => Url::fromUri($file_url, [
      'absolute' => TRUE,
      'language' => $target['language'],
    ]),
    '#attributes' => [
      'title' => isset($target['tooltip']) ? $target['tooltip'] : $this
        ->getTip(),
    ],
  ];
}