file_validate example

// Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      $violations = new EntityConstraintViolationList($file);
      $translator = new DrupalTranslator();
      $entity = EntityAdapter::createFromEntity($file);
      foreach ($errors as $error) {
        $violation = new ConstraintViolation($translator->trans($error),
          $error,
          [],
          $entity,
          '',
          NULL
        );


    // This will be replaced later with a filename based on the destination.     $file->setFilename($filename);
    $file->setMimeType($mimeType);
    $file->setSize($uploadedFile->getSize());

    // Add in our check of the file name length.     $validators['file_validate_name_length'] = [];

    // Call the validation functions specified by this function's caller.     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      throw new FileValidationException('File validation failed', $filename$errors);
    }

    $file->setFileUri($destinationFilename);

    if (!$this->moveUploadedFile($uploadedFile$file->getFileUri())) {
      throw new FileWriteException('File upload error. Could not move uploaded file.');
    }

    // Update the filename with any changes as a result of security or renaming

  protected function validate(FileInterface $file, array $validators) {
    $violations = $file->validate();

    // Remove violations of inaccessible fields as they cannot stem from our     // changes.     $violations->filterByFieldAccess();

    // Validate the file based on the field definition configuration.     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      $translator = new DrupalTranslator();
      foreach ($errors as $error) {
        $violation = new ConstraintViolation($translator->trans($error),
          (string) $error,
          [],
          EntityAdapter::createFromEntity($file),
          '',
          NULL
        );
        $violations->add($violation);
      }

class ValidateTest extends FileManagedUnitTestBase {

  /** * Tests that the validators passed into are checked. */
  public function testCallerValidation() {
    $file = $this->createFile();

    // Empty validators.     $this->assertEquals([]file_validate($file[]), 'Validating an empty array works successfully.');
    $this->assertFileHooksCalled(['validate']);

    // Use the file_test.module's test validator to ensure that passing tests     // return correctly.     file_test_reset();
    file_test_set_return('validate', []);
    $passing = ['file_test_validator' => [[]]];
    $this->assertEquals([]file_validate($file$passing), 'Validating passes.');
    $this->assertFileHooksCalled(['validate']);

    // Now test for failures in validators passed in and by hook_validate.
// Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383     $errors = file_validate($file$validators);

    if (!empty($errors)) {
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map([PlainTextOutput::class, 'renderFromHtml']$errors));

      throw new UnprocessableEntityHttpException($message);
    }

    $file->setFileUri($file_uri);
    // Move the file to the correct location after validation. Use     // FileSystemInterface::EXISTS_ERROR as the file location has already been
// Always respect the configured maximum file size.     $field_settings = $value->getFieldDefinition()->getSettings();
    if (array_key_exists('max_filesize', $field_settings)) {
      $validators['file_validate_size'] = [Bytes::toNumber($field_settings['max_filesize'])];
    }
    else {
      // Do not validate the file size if it is not set explicitly.       unset($validators['file_validate_size']);
    }

    // Checks that a file meets the criteria specified by the validators.     if ($errors = file_validate($file$validators)) {
      foreach ($errors as $error) {
        $this->context->addViolation($error);
      }
    }
  }

}
Home | Imprint | This part of the site doesn't use cookies.