You are here

class FileUrlHandler in File URL 8

Same name and namespace in other branches
  1. 2.0.x src/FileUrlHandler.php \Drupal\file_url\FileUrlHandler

Helper class for turning files into public URLs and back.

Hierarchy

Expanded class hierarchy of FileUrlHandler

3 files declare their use of FileUrlHandler
FileUrlFieldItemList.php in src/Plugin/Field/FieldType/FileUrlFieldItemList.php
FileUrlFormatter.php in src/Plugin/Field/FieldFormatter/FileUrlFormatter.php
FileUrlWidget.php in src/Plugin/Field/FieldWidget/FileUrlWidget.php
1 string reference to 'FileUrlHandler'
file_url.services.yml in ./file_url.services.yml
file_url.services.yml
1 service uses FileUrlHandler
file_url.handler in ./file_url.services.yml
Drupal\file_url\FileUrlHandler

File

src/FileUrlHandler.php, line 12

Namespace

Drupal\file_url
View source
class FileUrlHandler {

  /**
   * Get public dereferenceable URL from file.
   *
   * @param \Drupal\file\FileInterface $file
   *   File.
   *
   * @return string
   *   URL.
   *
   * @throws \Exception
   *   When a RemoteFile has been accidentally passed.
   */
  public static function fileToUrl(FileInterface $file) {
    global $base_url;
    if ($file instanceof RemoteFile) {
      throw new \Exception('Only regular files can be converted.');
    }
    $settings = \Drupal::configFactory()
      ->get('file_url.settings');
    $host = rtrim($settings
      ->get('dereference_host'));
    $host = $host ?: $base_url;

    // @see file_url.routing.yml for dereference redirect.
    return $host . '/file-dereference/' . $file
      ->id();
  }

  /**
   * Get the right file object from an URL.
   *
   * @param string $url
   *   URL.
   *
   * @return \Drupal\file\FileInterface
   *   The file object.
   */
  public static function urlToFile($url) {

    // Not a url, but a normal file ID. This can occurs when an object is
    // created in code (not through a form).
    if (is_numeric($url)) {
      return File::load($url);
    }
    $matches = [];
    preg_match('/\\/file-dereference\\/([0-9]+)/', $url, $matches);
    if (!empty($matches)) {
      return File::load($matches[1]);
    }
    return RemoteFile::load($url);
  }

  /**
   * Checks if a file entity is s remote file.
   *
   * @param \Drupal\file\FileInterface $file
   *   The file being checked.
   *
   * @return bool
   *   TRUE if it's a remote file.
   */
  public static function isRemote(FileInterface $file) {
    return $file instanceof RemoteFile;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FileUrlHandler::fileToUrl public static function Get public dereferenceable URL from file.
FileUrlHandler::isRemote public static function Checks if a file entity is s remote file.
FileUrlHandler::urlToFile public static function Get the right file object from an URL.