function FileExampleFileHelper::getExternalUrl

Prepare Url objects to prevent exceptions by the URL generator.

Helper function to get us an external URL if this is legal, and to catch the exception Drupal throws if this is not possible.

The URL generator is very sensitive to how you set things up, and some functions, in particular LinkGeneratorTrait::l(), will throw exceptions if you deviate from what's expected. This function will raise the chances your URL will be valid, and not do this.

Parameters

\Drupal\file\Entity\File|string $file_object: A file entity object.

Return value

\Drupal\Core\Url|bool A Url object that can be displayed as an internal URL.

File

modules/file_example/src/FileExampleFileHelper.php, line 82

Class

FileExampleFileHelper
A file helper class for file_example.

Namespace

Drupal\file_example

Code

public function getExternalUrl($file_object) {
    if ($file_object instanceof FileInterface) {
        $uri = $file_object->getFileUri();
    }
    else {
        // A little tricky, since file.inc is a little inconsistent, but often
        // this is a Uri.
        $uri = $this->fileUrlGenerator
            ->generateAbsoluteString($file_object);
    }
    try {
        // If we have been given a PHP stream URI, ask the stream itself if it
        // knows how to create an external URL.
        $wrapper = $this->streamWrapperManager
            ->getViaUri($uri);
        if ($wrapper) {
            $external_url = $wrapper->getExternalUrl();
            // Some streams may not have the concept of an external URL, so we
            // check here to make sure, since the example assumes this.
            if ($external_url) {
                $url = Url::fromUri($external_url);
                return $url;
            }
        }
        else {
            $url = Url::fromUri($uri);
            // If we did not throw on ::fromUri (you can), we return the URL.
            return $url;
        }
    } catch (\Throwable $e) {
        return FALSE;
    }
    return FALSE;
}