You are here

public function Media::getUrl in Linkit 8.5

Get the URL associated with a given entity.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity to get a URL for.

Return value

\Drupal\Core\GeneratedUrl A url to replace.

Overrides SubstitutionInterface::getUrl

File

src/Plugin/Linkit/Substitution/Media.php, line 40

Class

Media
A substitution plugin for the URL to a file.

Namespace

Drupal\linkit\Plugin\Linkit\Substitution

Code

public function getUrl(EntityInterface $entity) {
  $url = new GeneratedUrl();
  if (!$entity instanceof MediaInterface) {
    return $url;
  }
  $source_field = $entity
    ->getSource()
    ->getSourceFieldDefinition($entity
    ->get('bundle')->entity);
  if ($source_field && $entity
    ->hasField($source_field
    ->getName()) && $entity
    ->get($source_field
    ->getName())->entity instanceof FileInterface) {

    /** @var \Drupal\file\FileInterface $file */
    $file = $entity
      ->get($source_field
      ->getName())->entity;
    $url
      ->setGeneratedUrl(file_create_url($file
      ->getFileUri()));
    $url
      ->addCacheableDependency($entity);
    return $url;
  }

  // If available, fall back to the canonical URL if the bundle doesn't have
  // a file source field.
  if ($entity
    ->getEntityType()
    ->getLinkTemplate('canonical') != $entity
    ->getEntityType()
    ->getLinkTemplate('edit-form')) {
    return $entity
      ->toUrl('canonical')
      ->toString(TRUE);
  }
  return $url;
}