function FileValidator::validate

Same name and namespace in other branches
  1. 10 core/modules/file/src/Validation/FileValidator.php \Drupal\file\Validation\FileValidator::validate()

Validates a File with a list of validators.

Parameters

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

array $validators: An associative array of validators with:

  • key: the plugin ID of the file validation constraint.
  • value: an associative array of options to pass to the constraint.

Return value

\Symfony\Component\Validator\ConstraintViolationListInterface The violations list.

Overrides FileValidatorInterface::validate

File

core/modules/file/src/Validation/FileValidator.php, line 39

Class

FileValidator
Provides a class for file validation.

Namespace

Drupal\file\Validation

Code

public function validate(FileInterface $file, array $validators) : ConstraintViolationListInterface {
  $constraints = [];
  foreach ($validators as $validator => $options) {
    // Create the constraint.
    // Options are an associative array of constraint properties and values.
    $constraints[] = $this->constraintManager
      ->create($validator, $options);
  }
  // Get the typed data.
  $fileTypedData = $file->getTypedData();
  $violations = $this->validator
    ->validate($fileTypedData, $constraints);
  $this->eventDispatcher
    ->dispatch(new FileValidationEvent($file, $violations));
  // Always check the insecure upload constraint.
  if (count($violations) === 0) {
    $insecureUploadConstraint = $this->constraintManager
      ->create('FileExtensionSecure', []);
    $violations = $this->validator
      ->validate($fileTypedData, $insecureUploadConstraint);
  }
  return $violations;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.