function UploadedFileConstraintValidator::validate

Same name in other branches
  1. 11.x core/modules/file/src/Validation/Constraint/UploadedFileConstraintValidator.php \Drupal\file\Validation\Constraint\UploadedFileConstraintValidator::validate()

File

core/modules/file/src/Validation/Constraint/UploadedFileConstraintValidator.php, line 26

Class

UploadedFileConstraintValidator
Constraint validator for uploaded files.

Namespace

Drupal\file\Validation\Constraint

Code

public function validate(mixed $value, Constraint $constraint) {
    if (!$constraint instanceof UploadedFileConstraint) {
        throw new UnexpectedTypeException($constraint, UploadedFileConstraint::class);
    }
    if (!$value instanceof UploadedFile) {
        throw new UnexpectedTypeException($value, UploadedFile::class);
    }
    if ($value->isValid()) {
        return;
    }
    $maxSize = $constraint->maxSize ?? Environment::getUploadMaxSize();
    match ($value->getError()) {    \UPLOAD_ERR_INI_SIZE => $this->context
            ->buildViolation($constraint->uploadIniSizeErrorMessage, [
            '%file' => $value->getClientOriginalName(),
            '%maxsize' => ByteSizeMarkup::create($maxSize),
        ])
            ->setCode((string) \UPLOAD_ERR_INI_SIZE)
            ->addViolation(),
        \UPLOAD_ERR_FORM_SIZE => $this->context
            ->buildViolation($constraint->uploadFormSizeErrorMessage, [
            '%file' => $value->getClientOriginalName(),
            '%maxsize' => ByteSizeMarkup::create($maxSize),
        ])
            ->setCode((string) \UPLOAD_ERR_FORM_SIZE)
            ->addViolation(),
        \UPLOAD_ERR_PARTIAL => $this->context
            ->buildViolation($constraint->uploadPartialErrorMessage, [
            '%file' => $value->getClientOriginalName(),
        ])
            ->setCode((string) \UPLOAD_ERR_PARTIAL)
            ->addViolation(),
        \UPLOAD_ERR_NO_FILE => $this->context
            ->buildViolation($constraint->uploadNoFileErrorMessage, [
            '%file' => $value->getClientOriginalName(),
        ])
            ->setCode((string) \UPLOAD_ERR_NO_FILE)
            ->addViolation(),
        default => $this->context
            ->buildViolation($constraint->uploadErrorMessage, [
            '%file' => $value->getClientOriginalName(),
        ])
            ->setCode((string) $value->getError())
            ->addViolation(),
    
    };
}

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