You are here

function file_validate_size in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/file/file.module \file_validate_size()

Checks that the file's size is below certain limits.

Parameters

\Drupal\file\FileInterface $file: A file entity.

int $file_limit: An integer specifying the maximum file size in bytes. Zero indicates that no limit should be enforced.

int $user_limit: An integer specifying the maximum number of bytes the user is allowed. Zero indicates that no limit should be enforced.

Return value

array An array. If the file size exceeds limits, it will contain an error message.

See also

hook_file_validate()

1 call to file_validate_size()
ValidatorTest::testFileValidateSize in core/modules/file/src/Tests/ValidatorTest.php
Test file_validate_size().

File

core/modules/file/file.module, line 360
Defines a "managed_file" Form API field and a "file" field for Field module.

Code

function file_validate_size(FileInterface $file, $file_limit = 0, $user_limit = 0) {
  $user = \Drupal::currentUser();
  $errors = array();
  if ($file_limit && $file
    ->getSize() > $file_limit) {
    $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array(
      '%filesize' => format_size($file
        ->getSize()),
      '%maxsize' => format_size($file_limit),
    ));
  }

  // Save a query by only calling spaceUsed() when a limit is provided.
  if ($user_limit && \Drupal::entityManager()
    ->getStorage('file')
    ->spaceUsed($user
    ->id()) + $file
    ->getSize() > $user_limit) {
    $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array(
      '%filesize' => format_size($file
        ->getSize()),
      '%quota' => format_size($user_limit),
    ));
  }
  return $errors;
}