You are here

public function UrlExtractor::extractUrl in Twig Tweak 3.1.x

Same name and namespace in other branches
  1. 3.x src/UrlExtractor.php \Drupal\twig_tweak\UrlExtractor::extractUrl()

Extracts file URL from a string or object.

Parameters

string|object $input: Can be either file URI or an object that contains the URI.

bool $relative: (optional) Whether the URL should be root-relative, defaults to true.

Return value

string|null A URL that may be used to access the file.

File

src/UrlExtractor.php, line 45

Class

UrlExtractor
URL extractor service.

Namespace

Drupal\twig_tweak

Code

public function extractUrl($input, bool $relative = TRUE) : ?string {
  if (is_string($input)) {
    $url = file_create_url($input);
    return $relative ? file_url_transform_relative($url) : $url;
  }
  elseif ($input instanceof LinkItemInterface) {
    return $input
      ->getUrl()
      ->toString();
  }
  elseif ($input instanceof FieldItemList && $input
    ->first() instanceof LinkItemInterface) {
    return $input
      ->first()
      ->getUrl()
      ->toString();
  }
  $entity = $input;
  if ($input instanceof EntityReferenceFieldItemListInterface) {
    if ($item = $input
      ->first()) {
      $entity = $item->entity;
    }
  }
  elseif ($input instanceof EntityReferenceItem) {
    $entity = $input->entity;
  }

  // Drupal does not clean up references to deleted entities. So that the
  // entity property might be empty while the field item might not.
  // @see https://www.drupal.org/project/drupal/issues/2723323
  return $entity instanceof ContentEntityInterface ? $this
    ->getUrlFromEntity($entity, $relative) : NULL;
}