class FileUploadResource extends ResourceBase (View source)

File upload resource.

This is implemented as a field-level resource for the following reasons:

  • Validation for uploaded files is tied to fields (allowed extensions, max size, etc..).
  • The actual files do not need to be stored in another temporary location, to be later moved when they are referenced from a file field.
  • Permission to upload a file can be determined by a users field level create access to the file field.

Traits

Wrapper methods for \Drupal\Core\StringTranslation\TranslationInterface.

Provides dependency injection friendly methods for serialization.

Provides a trait for the messenger service.

Constants

DERIVATIVE_SEPARATOR

A string which is used to separate base plugin IDs from the derivative ID.

REQUEST_HEADER_FILENAME_REGEX

The regex used to extract the filename from the content disposition header.

BYTES_TO_READ

The amount of bytes to read in each iteration when streaming file data.

Properties

protected string $pluginId

The plugin_id.

from  PluginBase
protected array $pluginDefinition

The plugin implementation definition.

from  PluginBase
protected array $configuration

Configuration information passed into the plugin.

from  PluginBase
protected TranslationInterface $stringTranslation

The string translation service.

from  StringTranslationTrait
protected array $_serviceIds

An array of service IDs keyed by property name used for serialization.

from  DependencySerializationTrait
protected array $_entityStorages

An array of entity type IDs keyed by the property name of their storages.

from  DependencySerializationTrait
protected MessengerInterface $messenger

The messenger.

from  MessengerTrait
protected array $serializerFormats

The available serialization formats.

from  ResourceBase
protected LoggerInterface $logger

A logger instance.

from  ResourceBase
protected FileSystem $fileSystem

The file system service.

protected EntityTypeManagerInterface $entityTypeManager

The entity type manager.

protected EntityFieldManagerInterface $entityFieldManager

The entity field manager.

protected AccountInterface $currentUser

The currently authenticated user.

protected MimeTypeGuesserInterface $mimeTypeGuesser

The MIME type guesser.

protected Token $token

The token replacement instance.

protected LockBackendInterface $lock

The lock service.

protected ImmutableConfig $systemFileConfig
protected EventDispatcherInterface $eventDispatcher

The event dispatcher to dispatch the filename sanitize event.

Methods

__construct(array $configuration, string $plugin_id, mixed $plugin_definition, array $serializer_formats, LoggerInterface $logger, FileSystemInterface $file_system, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AccountInterface $current_user, MimeTypeGuesserInterface $mime_type_guesser, Token $token, LockBackendInterface $lock, Config $system_file_config, EventDispatcherInterface $event_dispatcher = NULL)

Constructs a FileUploadResource instance.

string
getPluginId()

Gets the plugin_id of the plugin instance.

string
getBaseId()

Gets the base_plugin_id of the plugin instance.

string|null
getDerivativeId()

Gets the derivative_id of the plugin instance.

array
getPluginDefinition()

Gets the definition of the plugin implementation.

bool
isConfigurable()

Determines if the plugin is configurable.

t(string $string, array $args = [], array $options = [])

Translates a string to the current language or to a given language.

formatPlural($count, $singular, $plural, array $args = [], array $options = [])

Formats a string containing a count of items.

getNumberOfPlurals($langcode = NULL)

Returns the number of plurals supported by a given language.

getStringTranslation()

Gets the string translation service.

$this
setStringTranslation(TranslationInterface $translation)

Sets the string translation service to use.

__sleep()

{@inheritdoc}

__wakeup()

{@inheritdoc}

setMessenger(MessengerInterface $messenger)

Sets the messenger.

messenger()

Gets the messenger.

create(ContainerInterface $container, array $configuration, string $plugin_id, mixed $plugin_definition)

Creates an instance of the plugin.

array
permissions()

Implements ResourceInterface::permissions().

RouteCollection
routes()

Returns a collection of routes with URL path information for the resource.

array
requestMethods()

Provides predefined HTTP request methods.

array
availableMethods()

Returns the available HTTP request methods on this plugin.

Route
getBaseRoute(string $canonical_path, string $method)

Gets the base route for a particular method.

array
getBaseRouteRequirements($method)

Gets the base route requirements for a particular method.

validate(FileInterface $file, array $validators)

Validates the file.

post(Request $request, string $entity_type_id, string $bundle, string $field_name)

Creates a file from an endpoint.

string
streamUploadData()

Streams file upload data to temporary file and moves to file destination.

string
validateAndParseContentDispositionHeader(Request $request)

Validates and extracts the filename from the Content-Disposition header.

validateAndLoadFieldDefinition(string $entity_type_id, string $bundle, string $field_name)

Validates and loads a field definition instance.

string
prepareFilename(string $filename, array $validators)

Prepares the filename to strip out any malicious extensions.

string
getUploadLocation(array $settings)

Determines the URI for a file field.

array
getUploadValidators(FieldDefinitionInterface $field_definition)

Retrieves the upload validators for a field definition.

static string
generateLockIdFromFileUri($file_uri)

Generates a lock ID based on the file URI.

Details

__construct(array $configuration, string $plugin_id, mixed $plugin_definition, array $serializer_formats, LoggerInterface $logger, FileSystemInterface $file_system, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AccountInterface $current_user, MimeTypeGuesserInterface $mime_type_guesser, Token $token, LockBackendInterface $lock, Config $system_file_config, EventDispatcherInterface $event_dispatcher = NULL)

Constructs a FileUploadResource instance.

Parameters

array $configuration

A configuration array containing information about the plugin instance.

string $plugin_id

The plugin_id for the plugin instance.

mixed $plugin_definition

The plugin implementation definition.

array $serializer_formats

The available serialization formats.

LoggerInterface $logger

A logger instance.

FileSystemInterface $file_system

The file system service.

EntityTypeManagerInterface $entity_type_manager

The entity type manager.

EntityFieldManagerInterface $entity_field_manager

The entity field manager.

AccountInterface $current_user

The currently authenticated user.

MimeTypeGuesserInterface $mime_type_guesser

The MIME type guesser.

Token $token

The token replacement instance.

LockBackendInterface $lock

The lock service.

Config $system_file_config

The system file configuration.

EventDispatcherInterface $event_dispatcher

The event dispatcher service.

string getPluginId()

Gets the plugin_id of the plugin instance.

Return Value

string

The plugin_id of the plugin instance.

string getBaseId()

Gets the base_plugin_id of the plugin instance.

Return Value

string

The base_plugin_id of the plugin instance.

string|null getDerivativeId()

Gets the derivative_id of the plugin instance.

Return Value

string|null

The derivative_id of the plugin instance NULL otherwise.

array getPluginDefinition()

Gets the definition of the plugin implementation.

Return Value

array

The plugin definition, as returned by the discovery object used by the plugin manager.

bool isConfigurable()

Determines if the plugin is configurable.

Return Value

bool

A boolean indicating whether the plugin is configurable.

protected TranslatableMarkup t(string $string, array $args = [], array $options = [])

Translates a string to the current language or to a given language.

See \Drupal\Core\StringTranslation\TranslatableMarkup::__construct() for important security information and usage guidelines.

In order for strings to be localized, make them available in one of the ways supported by the

Parameters

string $string

A string containing the English text to translate.

array $args

(optional) An associative array of replacements to make after translation. Based on the first character of the key, the value is escaped and/or themed. See \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for details.

array $options

(optional) An associative array of additional options, with the following elements:

  • 'langcode' (defaults to the current language): A language code, to translate to a language other than what is used to display the page.
  • 'context' (defaults to the empty context): The context the source string belongs to. See the @link i18n Internationalization topic @endlink for more information about string contexts.

Return Value

TranslatableMarkup

An object that, when cast to a string, returns the translated string.

See also

FormattableMarkup::placeholderFormat
TranslatableMarkup::__construct

protected formatPlural($count, $singular, $plural, array $args = [], array $options = [])

Formats a string containing a count of items.

Parameters

$count
$singular
$plural
array $args
array $options

See also

TranslationInterface::formatPlural

protected getNumberOfPlurals($langcode = NULL)

Returns the number of plurals supported by a given language.

Parameters

$langcode

See also

PluralFormulaInterface::getNumberOfPlurals

protected TranslationInterface getStringTranslation()

Gets the string translation service.

Return Value

TranslationInterface

The string translation service.

$this setStringTranslation(TranslationInterface $translation)

Sets the string translation service to use.

Parameters

TranslationInterface $translation

The string translation service.

Return Value

$this

__sleep()

{@inheritdoc}

__wakeup()

{@inheritdoc}

setMessenger(MessengerInterface $messenger)

Sets the messenger.

Parameters

MessengerInterface $messenger

The messenger.

MessengerInterface messenger()

Gets the messenger.

Return Value

MessengerInterface

The messenger.

static ContainerFactoryPluginInterface create(ContainerInterface $container, array $configuration, string $plugin_id, mixed $plugin_definition)

Creates an instance of the plugin.

Parameters

ContainerInterface $container

The container to pull out services used in the plugin.

array $configuration

A configuration array containing information about the plugin instance.

string $plugin_id

The plugin ID for the plugin instance.

mixed $plugin_definition

The plugin implementation definition.

Return Value

ContainerFactoryPluginInterface

Returns an instance of this plugin.

array permissions()

Implements ResourceInterface::permissions().

Every plugin operation method gets its own user permission. Example: "restful delete entity:node" with the title "Access DELETE on Node resource".

Return Value

array

The permission array.

RouteCollection routes()

Returns a collection of routes with URL path information for the resource.

This method determines where a resource is reachable, what path replacements are used, the required HTTP method for the operation etc.

Return Value

RouteCollection

A collection of routes that should be registered for this resource.

protected array requestMethods()

Provides predefined HTTP request methods.

Plugins can override this method to provide additional custom request methods.

Return Value

array

The list of allowed HTTP request method strings.

array availableMethods()

Returns the available HTTP request methods on this plugin.

Return Value

array

The list of supported methods. Example: array('GET', 'POST', 'PATCH').

protected Route getBaseRoute(string $canonical_path, string $method)

Gets the base route for a particular method.

Parameters

string $canonical_path

The canonical path for the resource.

string $method

The HTTP method to be used for the route.

Return Value

Route

The created base route.

protected array getBaseRouteRequirements($method)

Gets the base route requirements for a particular method.

Parameters

$method

The HTTP method to be used for the route.

Return Value

array

An array of requirements for parameters.

protected validate(FileInterface $file, array $validators)

Validates the file.

this method is unused in this class because file validation needs to be split up in 2 steps in ::post(). Add a deprecation notice as soon as a central core file upload service can be used in this class. See https://www.drupal.org/project/drupal/issues/2940383

Parameters

FileInterface $file

The file entity to validate.

array $validators

An array of upload validators to pass to file_validate().

Exceptions

UnprocessableEntityHttpException

ModifiedResourceResponse post(Request $request, string $entity_type_id, string $bundle, string $field_name)

Creates a file from an endpoint.

Parameters

Request $request

The current request.

string $entity_type_id

The entity type ID.

string $bundle

The entity bundle. This will be the same as $entity_type_id for entity types that don't support bundles.

string $field_name

The field name.

Return Value

ModifiedResourceResponse

A 201 response, on success.

Exceptions

HttpException

protected string streamUploadData()

Streams file upload data to temporary file and moves to file destination.

Return Value

string

The temp file path.

Exceptions

HttpException

protected string validateAndParseContentDispositionHeader(Request $request)

Validates and extracts the filename from the Content-Disposition header.

Parameters

Request $request

The request object.

Return Value

string

The filename extracted from the header.

Exceptions

BadRequestHttpException

protected FieldDefinitionInterface validateAndLoadFieldDefinition(string $entity_type_id, string $bundle, string $field_name)

Validates and loads a field definition instance.

Parameters

string $entity_type_id

The entity type ID the field is attached to.

string $bundle

The bundle the field is attached to.

string $field_name

The field name.

Return Value

FieldDefinitionInterface

The field definition.

Exceptions

BadRequestHttpException
AccessDeniedException

protected string prepareFilename(string $filename, array $validators)

Prepares the filename to strip out any malicious extensions.

Parameters

string $filename

The file name.

array $validators

The array of upload validators.

Return Value

string

The prepared/munged filename.

protected string getUploadLocation(array $settings)

Determines the URI for a file field.

Parameters

array $settings

The array of field settings.

Return Value

string

An un-sanitized file directory URI with tokens replaced. The result of the token replacement is then converted to plain text and returned.

protected array getUploadValidators(FieldDefinitionInterface $field_definition)

Retrieves the upload validators for a field definition.

This is copied from \Drupal\file\Plugin\Field\FieldType\FileItem as there is no entity instance available here that a FileItem would exist for.

Parameters

FieldDefinitionInterface $field_definition

The field definition for which to get validators.

Return Value

array

An array suitable for passing to file_save_upload() or the file field element's '#upload_validators' property.

static protected string generateLockIdFromFileUri($file_uri)

Generates a lock ID based on the file URI.

Parameters

$file_uri

The file URI.

Return Value

string

The generated lock ID.