file_bulkupload_translations-1.0.x-dev/src/Plugin/Validation/Constraint/UniqueLanguageConstraintValidator.php
src/Plugin/Validation/Constraint/UniqueLanguageConstraintValidator.php
<?php
declare(strict_types=1);
namespace Drupal\file_bulkupload_translations\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Drupal\file\FileInterface;
/**
* ConstraintValidator to avoid files with the same language when limited to 1.
*/
class UniqueLanguageConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Constructs a new Multiupload Translation Handler.
*
* @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
* The language manager.
*/
public function __construct(LanguageManagerInterface $languageManager) {
$this->languageManager = $languageManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function validate(mixed $value, Constraint $constraint) {
$filename_languages = [];
if(is_array($value)) {
foreach ($value as $item) {
$this->validate($item, $constraint);
}
}
if ($value instanceof FileInterface) {
// Get the language code from the filename.
$filename_language = $this->getLangCodeByFilename($value->getFilename());
// Check if the language of the file already exists in the array.
if (in_array($filename_language, $filename_languages)) {
// Add a violation if the language is already present.
$this->context->addViolation($constraint::NOT_UNIQUE, ['%filename_language' => $filename_language]);
return;
}
// Add the file's language to the array.
$filename_languages[] = $filename_language;
}
}
/**
* Get the filename language.
*/
private function getLangCodeByFilename(string $filename): string {
$config = \Drupal::config('file_bulkupload_translations.settings');
// Use regex to extract the language suffix from the filename.
if (preg_match($config->get('regex'), str_replace(' ', '', $filename), $match)) {
return mb_strtolower($match[1]);
}
// Return the default language code if no language is found.
return $this->languageManager->getDefaultLanguage()->getId();
}
}
