Files
2026-09-15 10:35:56 +08:00

81 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class LocaleResolver
{
private const LOCALE_PATH = 'general/locale/code';
private const DEFAULT_SOURCE_LANGUAGE_PATH =
'esun_multilocale_translation/general/default_source_language';
private const GOOGLE_LANGUAGE_MAP = [
'zh_CN' => 'zh-CN',
'zh_Hans_CN' => 'zh-CN',
'zh_TW' => 'zh-TW',
'zh_Hant_TW' => 'zh-TW',
'nb_NO' => 'no',
];
private const DEEPL_TARGET_LANGUAGE_MAP = [
'en_US' => 'EN-US',
'en_GB' => 'EN-GB',
'en_AU' => 'EN-GB',
'pt_BR' => 'PT-BR',
'pt_PT' => 'PT-PT',
'zh_CN' => 'ZH-HANS',
'zh_Hans_CN' => 'ZH-HANS',
'zh_TW' => 'ZH-HANT',
'zh_Hant_TW' => 'ZH-HANT',
];
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
{
}
public function getLanguageCode(int $storeId, string $provider, bool $target): string
{
if ($storeId <= 0) {
$locale = (string)$this->scopeConfig->getValue(self::DEFAULT_SOURCE_LANGUAGE_PATH);
} else {
$locale = (string)$this->scopeConfig->getValue(
self::LOCALE_PATH,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
if ($locale === '') {
throw new \RuntimeException((string)__('The Locale is not configured for this Store View.'));
}
if ($provider === 'deepl') {
if ($target && isset(self::DEEPL_TARGET_LANGUAGE_MAP[$locale])) {
return self::DEEPL_TARGET_LANGUAGE_MAP[$locale];
}
return strtoupper($this->getBaseLanguage($locale));
}
if (isset(self::GOOGLE_LANGUAGE_MAP[$locale])) {
return self::GOOGLE_LANGUAGE_MAP[$locale];
}
return $this->getBaseLanguage($locale);
}
private function getBaseLanguage(string $locale): string
{
$parts = preg_split('/[_-]/', $locale);
$language = strtolower((string)($parts[0] ?? ''));
if ($language === '') {
throw new \RuntimeException((string)__('Invalid Locale "%1".', $locale));
}
return $language;
}
}