Skip to content
Snippets Groups Projects
Verified Commit 82c59f84 authored by Lee Rowlands's avatar Lee Rowlands
Browse files

Issue #3389447 by kim.pepper, smustgrave, quietone: Provide a trait to create...

Issue #3389447 by kim.pepper, smustgrave, quietone: Provide a trait to create file upload validators from file field settings
parent 56b614e7
No related branches found
No related tags found
38 merge requests!8528Issue #3456871 by Tim Bozeman: Support NULL services,!8323Fix source code editing and in place front page site studio editing.,!6278Issue #3187770 by godotislate, smustgrave, catch, quietone: Views Rendered...,!54479.5.x SF update,!3878Removed unused condition head title for views,!38582585169-10.1.x,!3818Issue #2140179: $entity->original gets stale between updates,!3742Issue #3328429: Create item list field formatter for displaying ordered and unordered lists,!3731Claro: role=button on status report items,!3668Resolve #3347842 "Deprecate the trusted",!3651Issue #3347736: Create new SDC component for Olivero (header-search),!3546refactored dialog.pcss file,!3531Issue #3336994: StringFormatter always displays links to entity even if the user in context does not have access,!3502Issue #3335308: Confusing behavior with FormState::setFormState and FormState::setMethod,!3452Issue #3332701: Refactor Claro's tablesort-indicator stylesheet,!3355Issue #3209129: Scrolling problems when adding a block via layout builder,!3226Issue #2987537: Custom menu link entity type should not declare "bundle" entity key,!3154Fixes #2987987 - CSRF token validation broken on routes with optional parameters.,!3147Issue #3328457: Replace most substr($a, $i) where $i is negative with str_ends_with(),!3146Issue #3328456: Replace substr($a, 0, $i) with str_starts_with(),!3133core/modules/system/css/components/hidden.module.css,!2964Issue #2865710 : Dependencies from only one instance of a widget are used in display modes,!2812Issue #3312049: [Followup] Fix Drupal.Commenting.FunctionComment.MissingReturnType returns for NULL,!2614Issue #2981326: Replace non-test usages of \Drupal::logger() with IoC injection,!2378Issue #2875033: Optimize joins and table selection in SQL entity query implementation,!2334Issue #3228209: Add hasRole() method to AccountInterface,!2062Issue #3246454: Add weekly granularity to views date sort,!1255Issue #3238922: Refactor (if feasible) uses of the jQuery serialize function to use vanillaJS,!1105Issue #3025039: New non translatable field on translatable content throws error,!1073issue #3191727: Focus states on mobile second level navigation items fixed,!10223132456: Fix issue where views instances are emptied before an ajax request is complete,!877Issue #2708101: Default value for link text is not saved,!844Resolve #3036010 "Updaters",!673Issue #3214208: FinishResponseSubscriber could create duplicate headers,!617Issue #3043725: Provide a Entity Handler for user cancelation,!579Issue #2230909: Simple decimals fail to pass validation,!560Move callback classRemove outside of the loop,!555Issue #3202493
Pipeline #48533 passed
Pipeline: drupal

#48534

    ...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
    use Drupal\Core\StringTranslation\ByteSizeMarkup; use Drupal\Core\StringTranslation\ByteSizeMarkup;
    use Drupal\Core\StringTranslation\TranslatableMarkup; use Drupal\Core\StringTranslation\TranslatableMarkup;
    use Drupal\Core\TypedData\DataDefinition; use Drupal\Core\TypedData\DataDefinition;
    use Drupal\file\Validation\FileValidatorSettingsTrait;
    /** /**
    * Plugin implementation of the 'file' field type. * Plugin implementation of the 'file' field type.
    ...@@ -35,6 +36,8 @@ ...@@ -35,6 +36,8 @@
    */ */
    class FileItem extends EntityReferenceItem { class FileItem extends EntityReferenceItem {
    use FileValidatorSettingsTrait;
    /** /**
    * {@inheritdoc} * {@inheritdoc}
    */ */
    ...@@ -327,24 +330,7 @@ protected static function doGetUploadLocation(array $settings, $data = []) { ...@@ -327,24 +330,7 @@ protected static function doGetUploadLocation(array $settings, $data = []) {
    * element's '#upload_validators' property. * element's '#upload_validators' property.
    */ */
    public function getUploadValidators() { public function getUploadValidators() {
    $validators = []; return $this->getFileUploadValidators($this->getSettings());
    $settings = $this->getSettings();
    // Cap the upload size according to the PHP limit.
    $max_filesize = Bytes::toNumber(Environment::getUploadMaxSize());
    if (!empty($settings['max_filesize'])) {
    $max_filesize = min($max_filesize, Bytes::toNumber($settings['max_filesize']));
    }
    // There is always a file size limit due to the PHP server limit.
    $validators['FileSizeLimit'] = ['fileLimit' => $max_filesize];
    // Add the extension check if necessary.
    if (!empty($settings['file_extensions'])) {
    $validators['FileExtension'] = ['extensions' => $settings['file_extensions']];
    }
    return $validators;
    } }
    /** /**
    ......
    ...@@ -3,13 +3,10 @@ ...@@ -3,13 +3,10 @@
    namespace Drupal\file\Plugin\rest\resource; namespace Drupal\file\Plugin\rest\resource;
    use Drupal\Component\Render\PlainTextOutput; use Drupal\Component\Render\PlainTextOutput;
    use Drupal\Component\Utility\Bytes;
    use Drupal\Component\Utility\Crypt; use Drupal\Component\Utility\Crypt;
    use Drupal\Component\Utility\Environment;
    use Drupal\Core\Config\Config; use Drupal\Core\Config\Config;
    use Drupal\Core\Entity\EntityFieldManagerInterface; use Drupal\Core\Entity\EntityFieldManagerInterface;
    use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\EntityTypeManagerInterface;
    use Drupal\Core\Field\FieldDefinitionInterface;
    use Drupal\Core\File\Event\FileUploadSanitizeNameEvent; use Drupal\Core\File\Event\FileUploadSanitizeNameEvent;
    use Drupal\Core\File\Exception\FileException; use Drupal\Core\File\Exception\FileException;
    use Drupal\Core\File\FileSystemInterface; use Drupal\Core\File\FileSystemInterface;
    ...@@ -20,6 +17,7 @@ ...@@ -20,6 +17,7 @@
    use Drupal\file\Upload\ContentDispositionFilenameParser; use Drupal\file\Upload\ContentDispositionFilenameParser;
    use Drupal\file\Upload\InputStreamFileWriterInterface; use Drupal\file\Upload\InputStreamFileWriterInterface;
    use Drupal\file\Validation\FileValidatorInterface; use Drupal\file\Validation\FileValidatorInterface;
    use Drupal\file\Validation\FileValidatorSettingsTrait;
    use Drupal\rest\ModifiedResourceResponse; use Drupal\rest\ModifiedResourceResponse;
    use Drupal\rest\Plugin\ResourceBase; use Drupal\rest\Plugin\ResourceBase;
    use Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait; use Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait;
    ...@@ -59,6 +57,7 @@ ...@@ -59,6 +57,7 @@
    */ */
    class FileUploadResource extends ResourceBase { class FileUploadResource extends ResourceBase {
    use FileValidatorSettingsTrait;
    use EntityResourceValidationTrait { use EntityResourceValidationTrait {
    validate as resourceValidate; validate as resourceValidate;
    } }
    ...@@ -282,7 +281,7 @@ public function post(Request $request, $entity_type_id, $bundle, $field_name) { ...@@ -282,7 +281,7 @@ public function post(Request $request, $entity_type_id, $bundle, $field_name) {
    throw new HttpException(500, 'Destination file path is not writable'); throw new HttpException(500, 'Destination file path is not writable');
    } }
    $validators = $this->getUploadValidators($field_definition); $validators = $this->getFileUploadValidators($field_definition->getSettings());
    $prepared_filename = $this->prepareFilename($filename, $validators); $prepared_filename = $this->prepareFilename($filename, $validators);
    ...@@ -488,47 +487,6 @@ protected function getUploadLocation(array $settings) { ...@@ -488,47 +487,6 @@ protected function getUploadLocation(array $settings) {
    return $settings['uri_scheme'] . '://' . $destination; return $settings['uri_scheme'] . '://' . $destination;
    } }
    /**
    * 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.
    *
    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
    * The field definition for which to get validators.
    *
    * @return array
    * An array suitable for passing to file_save_upload() or the file field
    * element's '#upload_validators' property.
    */
    protected function getUploadValidators(FieldDefinitionInterface $field_definition) {
    $validators = [
    // Add in our check of the file name length.
    'FileNameLength' => [],
    ];
    $settings = $field_definition->getSettings();
    // Cap the upload size according to the PHP limit.
    $max_filesize = Bytes::toNumber(Environment::getUploadMaxSize());
    if (!empty($settings['max_filesize'])) {
    $max_filesize = min($max_filesize, Bytes::toNumber($settings['max_filesize']));
    }
    // There is always a file size limit due to the PHP server limit.
    $validators['FileSizeLimit'] = [
    'fileLimit' => $max_filesize,
    ];
    // Add the extension check if necessary.
    if (!empty($settings['file_extensions'])) {
    $validators['FileExtension'] = [
    'extensions' => $settings['file_extensions'],
    ];
    }
    return $validators;
    }
    /** /**
    * {@inheritdoc} * {@inheritdoc}
    */ */
    ......
    <?php
    namespace Drupal\file\Validation;
    use Drupal\Component\Utility\Bytes;
    use Drupal\Component\Utility\Environment;
    /**
    * Provides a trait to create validators from settings.
    */
    trait FileValidatorSettingsTrait {
    /**
    * Gets the upload validators for the specified settings.
    *
    * @param array $settings
    * An associative array of settings. The following keys are supported:
    * - max_filesize: The maximum file size in bytes. Defaults to the PHP max
    * upload size.
    * - file_extensions: A space-separated list of allowed file extensions.
    *
    * @return array
    * An array suitable for passing to file_save_upload() or the file field
    * element's '#upload_validators' property.
    */
    public function getFileUploadValidators(array $settings): array {
    $validators = [
    // Add in our check of the file name length.
    'FileNameLength' => [],
    ];
    // Cap the upload size according to the PHP limit.
    $maxFilesize = Bytes::toNumber(Environment::getUploadMaxSize());
    if (!empty($settings['max_filesize'])) {
    $maxFilesize = min($maxFilesize, Bytes::toNumber($settings['max_filesize']));
    }
    // There is always a file size limit due to the PHP server limit.
    $validators['FileSizeLimit'] = ['fileLimit' => $maxFilesize];
    // Add the extension check if necessary.
    if (!empty($settings['file_extensions'])) {
    $validators['FileExtension'] = [
    'extensions' => $settings['file_extensions'],
    ];
    }
    return $validators;
    }
    }
    ...@@ -3,9 +3,7 @@ ...@@ -3,9 +3,7 @@
    namespace Drupal\jsonapi\Controller; namespace Drupal\jsonapi\Controller;
    use Drupal\Component\Render\PlainTextOutput; use Drupal\Component\Render\PlainTextOutput;
    use Drupal\Component\Utility\Bytes;
    use Drupal\Component\Utility\Crypt; use Drupal\Component\Utility\Crypt;
    use Drupal\Component\Utility\Environment;
    use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Config\ConfigFactoryInterface;
    use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityInterface;
    use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\Core\Field\FieldDefinitionInterface;
    ...@@ -22,6 +20,7 @@ ...@@ -22,6 +20,7 @@
    use Drupal\file\Upload\ContentDispositionFilenameParser; use Drupal\file\Upload\ContentDispositionFilenameParser;
    use Drupal\file\Upload\InputStreamFileWriterInterface; use Drupal\file\Upload\InputStreamFileWriterInterface;
    use Drupal\file\Validation\FileValidatorInterface; use Drupal\file\Validation\FileValidatorInterface;
    use Drupal\file\Validation\FileValidatorSettingsTrait;
    use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
    use Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException; use Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException;
    use Symfony\Component\HttpFoundation\File\Exception\NoFileException; use Symfony\Component\HttpFoundation\File\Exception\NoFileException;
    ...@@ -45,6 +44,8 @@ ...@@ -45,6 +44,8 @@
    */ */
    class TemporaryJsonapiFileFieldUploader { class TemporaryJsonapiFileFieldUploader {
    use FileValidatorSettingsTrait;
    /** /**
    * The regex used to extract the filename from the content disposition header. * The regex used to extract the filename from the content disposition header.
    * *
    ...@@ -200,7 +201,7 @@ public function handleFileUploadForField(FieldDefinitionInterface $field_definit ...@@ -200,7 +201,7 @@ public function handleFileUploadForField(FieldDefinitionInterface $field_definit
    throw new HttpException(500, 'Destination file path is not writable'); throw new HttpException(500, 'Destination file path is not writable');
    } }
    $validators = $this->getUploadValidators($field_definition); $validators = $this->getFileUploadValidators($field_definition->getSettings());
    $prepared_filename = $this->prepareFilename($filename, $validators); $prepared_filename = $this->prepareFilename($filename, $validators);
    ...@@ -423,45 +424,6 @@ protected function getUploadLocation(array $settings) { ...@@ -423,45 +424,6 @@ protected function getUploadLocation(array $settings) {
    return $settings['uri_scheme'] . '://' . $destination; return $settings['uri_scheme'] . '://' . $destination;
    } }
    /**
    * 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.
    *
    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
    * The field definition for which to get validators.
    *
    * @return array
    * An array suitable for passing to file_save_upload() or the file field
    * element's '#upload_validators' property.
    */
    protected function getUploadValidators(FieldDefinitionInterface $field_definition) {
    $validators = [
    // Add in our check of the file name length.
    'FileNameLength' => [],
    ];
    $settings = $field_definition->getSettings();
    // Cap the upload size according to the PHP limit.
    $max_filesize = Bytes::toNumber(Environment::getUploadMaxSize());
    if (!empty($settings['max_filesize'])) {
    $max_filesize = min($max_filesize, Bytes::toNumber($settings['max_filesize']));
    }
    // There is always a file size limit due to the PHP server limit.
    $validators['FileSizeLimit'] = ['fileLimit' => $max_filesize];
    // Add the extension check if necessary.
    if (!empty($settings['file_extensions'])) {
    $validators['FileExtension'] = [
    'extensions' => $settings['file_extensions'],
    ];
    }
    return $validators;
    }
    /** /**
    * Generates a lock ID based on the file URI. * Generates a lock ID based on the file URI.
    * *
    ......
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment