diff --git a/Classes/Configuration/Configuration.php b/Classes/Configuration/Configuration.php index 3d2730a..9ff2947 100644 --- a/Classes/Configuration/Configuration.php +++ b/Classes/Configuration/Configuration.php @@ -105,6 +105,14 @@ public function getGlossaryForLanguagePair(string $sourceLangage, string $target return $this->glossaries[$key] ?? null; } + /** + * Fetches amount of glossaries. + */ + public function getCountGlossaries(Translator $translator): int + { + return count($translator->listGlossaries()); + } + /** * Fetches maximum number of glossaries per language pair. * diff --git a/Classes/Service/DeeplTranslationService.php b/Classes/Service/DeeplTranslationService.php index 8124d77..0ca497c 100644 --- a/Classes/Service/DeeplTranslationService.php +++ b/Classes/Service/DeeplTranslationService.php @@ -78,6 +78,8 @@ class DeeplTranslationService implements SingletonInterface protected array $targetLanguages = []; protected ?Translator $translator = null; + + protected bool $autoDetectSourceLang = false; /** * Creates the instance of the class. @@ -384,6 +386,18 @@ public function translateText(string $text, string $sourceLanguage, string $targ TranslateTextOptions::PRESERVE_FORMATTING => true, TranslateTextOptions::TAG_HANDLING => 'html', ]; + + // only necessary for autodetect with potential glossary, + // otherwise passing null below is sufficient + if ($this->autoDetectSourceLang && $this->configuration->getCountGlossaries($this->translator) > 0) { + $sourceLanguage = $this->translator->translateText( + $text, + null, + $targetLanguage, + $options + )->detectedSourceLang; + } + [$sourceLanguageForGlossary] = explode('-', $sourceLanguage); [$targetLanguageForGlossary] = explode('-', $targetLanguage); $glossary = $this->configuration->getGlossaryForLanguagePair($sourceLanguageForGlossary, $targetLanguageForGlossary); @@ -393,7 +407,7 @@ public function translateText(string $text, string $sourceLanguage, string $targ return empty($text) ? '' : $this->translator->translateText( $text, - $sourceLanguage, + ($this->autoDetectSourceLang && !$sourceLanguage) ? null : $sourceLanguage, $targetLanguage, $options ); @@ -480,11 +494,11 @@ protected function canTranslate(SiteLanguage $sourceLanguage, SiteLanguage $targ } elseif (!$this->isSupportedLanguage($sourceLanguage, $this->sourceLanguages)) { $this->logger->notice( sprintf( - 'Language "%s" cannot be used as a source language because it is not supported', + 'Language "%s" is not supported as a source language. Will try to proceed using DeepL autodetection', $sourceLanguage->getLocale()->getLanguageCode() ) ); - $canTranslate = false; + $this->autoDetectSourceLang = true; } elseif (!$this->isSupportedLanguage($targetLanguage, $this->targetLanguages)) { $this->logger->notice( sprintf(