Skip to content

File

Provides helpers for working with files.


  • Full name: \Drupal\helper\File

Properties

entityTypeManager

protected \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager

mimeTypeGuesser

protected \Symfony\Component\Mime\MimeTypeGuesserInterface $mimeTypeGuesser

currentUser

protected \Drupal\Core\Session\AccountInterface $currentUser

httpClient

protected \GuzzleHttp\ClientInterface $httpClient

fileSystem

protected \Drupal\Core\File\FileSystemInterface $fileSystem

fileRepository

protected \Drupal\file\FileRepositoryInterface $fileRepository

eventDispatcher

protected \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher

Methods

__construct

File constructor.

public __construct(\Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager, \Symfony\Component\Mime\MimeTypeGuesserInterface $mimeTypeGuesser, \Drupal\Core\Session\AccountInterface $currentUser, \GuzzleHttp\ClientInterface $httpClient, \Drupal\Core\File\FileSystemInterface $fileSystem, \Drupal\file\FileRepositoryInterface $fileRepository, \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher): mixed

Parameters:

Parameter Type Description
$entityTypeManager \Drupal\Core\Entity\EntityTypeManagerInterface
The entity type manager.
$mimeTypeGuesser \Symfony\Component\Mime\MimeTypeGuesserInterface
The mime type guesser.
$currentUser \Drupal\Core\Session\AccountInterface
The current user.
$httpClient \GuzzleHttp\ClientInterface
The HTTP client.
$fileSystem \Drupal\Core\File\FileSystemInterface
The file system.
$fileRepository \Drupal\file\FileRepositoryInterface
The file repository.
$eventDispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface
The event dispatcher.

createOrReuseFromUri

Creates or reuses a file object based on a URI.

public createOrReuseFromUri(string $uri, bool $reuse_existing = true): \Drupal\file\FileInterface

Parameters:

Parameter Type Description
$uri string
A string containing the URI.
$reuse_existing bool
If TRUE will try to reuse an existing file with the same URI.
If FALSE will always create a new file.

Return Value:

A file object.


filterValidFiles

Filter callback; Permanent files or temporary files owned by current user.

public static filterValidFiles(\Drupal\file\FileInterface $file): bool
  • This method is static. Parameters:
Parameter Type Description
$file \Drupal\file\FileInterface
The file object.

Return Value:

TRUE if the file is valid, or FALSE otherwise.


isPermanentOrOwnedBy

Checks whether a file is permanent, or a temporary file owned by a user.

protected static isPermanentOrOwnedBy(\Drupal\file\FileInterface $file, \Drupal\Core\Session\AccountInterface $account): bool
  • This method is static. Parameters:
Parameter Type Description
$file \Drupal\file\FileInterface
The file object.
$account \Drupal\Core\Session\AccountInterface
The user account.

Return Value:

TRUE if the file is permanent or owned by the user, or FALSE otherwise.


isPublicUri

Checks whether a URI is on a public scheme.

public static isPublicUri(string $uri): bool

Follows core's FileDownloadController: the public scheme and the schemes in the file_additional_public_schemes setting are public, but private and temporary never are, even when they're listed in that setting. Only the scheme is checked, not where the file is: a public:// URI that's a symlink into the private files directory is still public. Paths without a scheme, such as absolute paths on the server, aren't public.

  • This method is static. Parameters:
Parameter Type Description
$uri string
The URI or path.

Return Value:

TRUE if the URI is on a public scheme, or FALSE otherwise.


getDataUri

Converts a file URL into a data URI.

public getDataUri(string $uri, bool $base_64_encode = true, string|null $mimetype = null): string

Parameters:

Parameter Type Description
$uri string
The file URI.
$base_64_encode bool
TRUE to return the data URI as base-64 encoded content.
$mimetype string|null
The optional mime type to provide for the data URI. If not provided
the mime type guesser service will be used.

Return Value:

The image data URI for use in a src attribute.

Throws:

If the file cannot be read. - AccessDeniedException


getExtensionFromResponse

Gets a file extension from an HTTP response's Content-Type header.

public static getExtensionFromResponse(\Psr\Http\Message\ResponseInterface $response): string|null

Parameters in the header, such as the charset, are ignored.

  • This method is static. Parameters:
Parameter Type Description
$response \Psr\Http\Message\ResponseInterface
The response.

Return Value:

The most common extension for the MIME type, such as "jpg" for image/jpeg, or NULL if the response has no Content-Type header or the MIME type is unknown.


downloadFromUrl

Downloads a remote file and saves it as a file entity.

public downloadFromUrl(string|\Psr\Http\Message\UriInterface $url, string $directory, string[]|null $allowedExtensions = null, \Drupal\Core\File\FileExists $fileExists = \Drupal\Core\File\FileExists::Rename, array $requestOptions = []): \Drupal\file\FileInterface

The file is streamed to a temporary file, so large files don't need to fit in memory. It is named after the filename in the response's Content-Disposition header, or else the last part of the final URL's path, after any redirects, or else a hash of the URL. If the name has no extension, one is added from the response's Content-Type header. The name is then sanitized with FileUploadSanitizeNameEvent, as for uploads.

Pass $allowedExtensions when saving files from a source you don't fully control, especially to public files: like uploads without an extension check, a download could otherwise be saved as an HTML or SVG file that runs scripts when it's viewed on the site.

Parameters:

Parameter Type Description
$url string|\Psr\Http\Message\UriInterface
The URL of the file.
$directory string
The directory to save the file in, such as "public://downloads". It is
created if it doesn't exist.
$allowedExtensions string[]|null
(optional) The file extensions that can be saved, such as ['jpg', 'png'].
Defaults to NULL, which allows any extension the upload sanitizer
allows: it renames script extensions such as .php to .txt, unless
insecure uploads are allowed.
$fileExists \Drupal\Core\File\FileExists
(optional) What to do if a file with the same name already exists.
Defaults to renaming the new file.
$requestOptions array
(optional) Guzzle request options, such as headers or a timeout. The
sink option is set by this method.

Return Value:

The saved file entity. It's permanent, as with FileRepositoryInterface::writeData(). To have cron delete it unless something uses it, call $file->setTemporary()->save().

Throws:

If the request fails, including error responses unless the http_errors request option is FALSE. - GuzzleException If the file has no extension and none can be found from the response, or its extension isn't allowed. - RuntimeException If the file can't be saved. - FileException


getFilenameFromResponse

Gets the filename from an HTTP response's Content-Disposition header.

protected static getFilenameFromResponse(\Psr\Http\Message\ResponseInterface $response): string|null
  • This method is static. Parameters:
Parameter Type Description
$response \Psr\Http\Message\ResponseInterface
The response.

Return Value:

The filename without any directories, preferring the encoded filename* parameter, or NULL if the header has no filename.