Drupal 11 will change many functionality related to file validation. One of the changes is the hook_file_validate() which is now deprecated since Drupal 10.2 and will be removed from Drupal 11.
This means when you have a file validation hook somewhere or you want to implement it, you should start using that event to prepare for the Drupal 11 upgrade, but how to implement that event?
So, assuming you want to disallow some specific file extension globally and prevent it from enabling on the configuration, you need something that runs for all file uploads - now there is a FileValidationEvent
, where you need to add a subscriber. It could look something like FileExtensionValidator below.
<?php
namespace Drupal\my_module\EventSubscriber;
use Drupal\file\Validation\FileValidationEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\ConstraintViolation;
class FileExtensionValidator implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [
FileValidationEvent::class => 'validateFileExtension',
];
}
/**
* Validate file extension.
*
* @param \Drupal\file\Validation\FileValidationEvent $event
* The file validation event.
*/
public function validateFileExtension(FileValidationEvent $event): void {
$file = $event->file;
$extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
if ($extension === 'txt') {
$event->violations->add(new ConstraintViolation(
'The file extension txt is not allowed.',
'The file extension txt is not allowed.',
[],
$file,
'file',
$file->getFilename(),
null,
'file_extension_not_allowed'));
}
}
}
This subscriber will check for the specific extension which is txt
in this case and will add a new constraint violation to the violations list if the uploaded file has such an extension.
Finally, let Drupal know about your new validation subscriber.
services:
my_module.file_extension_subscriber:
class: Drupal\my_module\EventSubscriber\FileExtensionValidator
tags:
- { name: event_subscriber }
To test this, rebuild the caches and try to upload a file, that has a txt
extension. It will say that this file is not allowed even when txt is an allowed file type.