You are here

function lightning_media_validate_upload in Lightning Media 8.2

Same name and namespace in other branches
  1. 8.4 lightning_media.module \lightning_media_validate_upload()
  2. 8 lightning_media.module \lightning_media_validate_upload()
  3. 8.3 lightning_media.module \lightning_media_validate_upload()

Validates a file using media entity source field criteria.

Parameters

\Drupal\file\FileInterface $file: The file to validate.

string[] $bundles: (optional) A set of media bundle IDs which might match the input. If omitted, all bundles to which the user has create access will be checked.

Return value

string[] An array of errors. If empty, the file passed validation.

File

./lightning_media.module, line 256
Core media asset support for Lightning.

Code

function lightning_media_validate_upload(FileInterface $file, array $bundles = []) {
  try {
    $entity = \Drupal::service('lightning.media_helper')
      ->createFromInput($file, $bundles);
  } catch (IndeterminateBundleException $e) {
    return [];
  }

  /** @var \Drupal\file\Plugin\Field\FieldType\FileItem $item */
  $item = MediaHelper::getSourceField($entity)
    ->first();
  $validators = [
    // It's maybe a bit overzealous to run this validator, but hey...better
    // safe than screwed over by script kiddies.
    'file_validate_name_length' => [],
  ];
  $validators = array_merge($validators, $item
    ->getUploadValidators());

  // This function is only called by the custom FileUpload widget, which runs
  // file_validate_extensions before this function. So there's no need to
  // validate the extensions again.
  unset($validators['file_validate_extensions']);

  // If this is an image field, add image validation. Against all sanity,
  // this is normally done by ImageWidget, not ImageItem, which is why we
  // need to facilitate this a bit.
  if ($item instanceof ImageItem) {

    // Validate that this is, indeed, a supported image.
    $validators['file_validate_is_image'] = [];
    $settings = $item
      ->getFieldDefinition()
      ->getSettings();
    if ($settings['max_resolution'] || $settings['min_resolution']) {
      $validators['file_validate_image_resolution'] = [
        $settings['max_resolution'],
        $settings['min_resolution'],
      ];
    }
  }
  return file_validate($file, $validators);
}