function FileSizeLimitConstraintValidator::validate

Same name in other branches
  1. 10 core/modules/file/src/Plugin/Validation/Constraint/FileSizeLimitConstraintValidator.php \Drupal\file\Plugin\Validation\Constraint\FileSizeLimitConstraintValidator::validate()

File

core/modules/file/src/Plugin/Validation/Constraint/FileSizeLimitConstraintValidator.php, line 44

Class

FileSizeLimitConstraintValidator
Validates the FileSizeLimitConstraint.

Namespace

Drupal\file\Plugin\Validation\Constraint

Code

public function validate(mixed $value, Constraint $constraint) : void {
    $file = $this->assertValueIsFile($value);
    if (!$constraint instanceof FileSizeLimitConstraint) {
        throw new UnexpectedTypeException($constraint, FileSizeLimitConstraint::class);
    }
    $fileLimit = $constraint->fileLimit;
    if ($fileLimit && $file->getSize() > $fileLimit) {
        $this->context
            ->addViolation($constraint->maxFileSizeMessage, [
            '%filesize' => ByteSizeMarkup::create($file->getSize()),
            '%maxsize' => ByteSizeMarkup::create($fileLimit),
        ]);
    }
    $userLimit = $constraint->userLimit;
    // Save a query by only calling spaceUsed() when a limit is provided.
    if ($userLimit) {
        
        /** @var \Drupal\file\FileStorageInterface $fileStorage */
        $fileStorage = $this->entityTypeManager
            ->getStorage('file');
        $spaceUsed = $fileStorage->spaceUsed($this->currentUser
            ->id()) + $file->getSize();
        if ($spaceUsed > $userLimit) {
            $this->context
                ->addViolation($constraint->diskQuotaMessage, [
                '%filesize' => ByteSizeMarkup::create($file->getSize()),
                '%quota' => ByteSizeMarkup::create($userLimit),
            ]);
        }
    }
}

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