You are here

public function FileBrowserWidget::getFileValidators in Entity Browser 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldWidget/FileBrowserWidget.php \Drupal\entity_browser\Plugin\Field\FieldWidget\FileBrowserWidget::getFileValidators()

Retrieves the upload validators for a file field.

This is a combination of logic shared between the File and Image widgets.

Parameters

bool $upload: Whether or not upload-specific validators should be returned.

Return value

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

1 call to FileBrowserWidget::getFileValidators()
FileBrowserWidget::getPersistentData in src/Plugin/Field/FieldWidget/FileBrowserWidget.php
Gets data that should persist across Entity Browser renders.

File

src/Plugin/Field/FieldWidget/FileBrowserWidget.php, line 486

Class

FileBrowserWidget
Entity browser file widget.

Namespace

Drupal\entity_browser\Plugin\Field\FieldWidget

Code

public function getFileValidators($upload = FALSE) {
  $validators = [];
  $settings = $this->fieldDefinition
    ->getSettings();
  if ($upload) {

    // Cap the upload size according to the PHP limit.
    $max_filesize = Bytes::toInt(Environment::getUploadMaxSize());
    if (!empty($settings['max_filesize'])) {
      $max_filesize = min($max_filesize, Bytes::toInt($settings['max_filesize']));
    }

    // There is always a file size limit due to the PHP server limit.
    $validators['file_validate_size'] = [
      $max_filesize,
    ];
  }

  // Images have expected defaults for file extensions.
  // See \Drupal\image\Plugin\Field\FieldWidget::formElement() for details.
  if ($this->fieldDefinition
    ->getType() == 'image') {

    // If not using custom extension validation, ensure this is an image.
    $supported_extensions = [
      'png',
      'gif',
      'jpg',
      'jpeg',
    ];
    $extensions = isset($settings['file_extensions']) ? $settings['file_extensions'] : implode(' ', $supported_extensions);
    $extensions = array_intersect(explode(' ', $extensions), $supported_extensions);
    $validators['file_validate_extensions'] = [
      implode(' ', $extensions),
    ];

    // Add resolution validation.
    if (!empty($settings['max_resolution']) || !empty($settings['min_resolution'])) {
      $validators['entity_browser_file_validate_image_resolution'] = [
        $settings['max_resolution'],
        $settings['min_resolution'],
      ];
    }
  }
  elseif (!empty($settings['file_extensions'])) {
    $validators['file_validate_extensions'] = [
      $settings['file_extensions'],
    ];
  }
  return $validators;
}