src/Core/System/Locale/LanguageLocaleCodeProvider.php line 24

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\System\Locale;
  3. use Shopware\Core\Framework\Log\Package;
  4. use Shopware\Core\Framework\Routing\Exception\LanguageNotFoundException;
  5. use Shopware\Core\System\Language\LanguageLoaderInterface;
  6. use Symfony\Contracts\Service\ResetInterface;
  7. #[Package('system-settings')]
  8. class LanguageLocaleCodeProvider implements ResetInterface
  9. {
  10.     private array $languages = [];
  11.     /**
  12.      * @internal
  13.      */
  14.     public function __construct(private readonly LanguageLoaderInterface $languageLoader)
  15.     {
  16.     }
  17.     public function getLocaleForLanguageId(string $languageId): string
  18.     {
  19.         $languages $this->getLanguages();
  20.         if (!\array_key_exists($languageId$languages)) {
  21.             throw new LanguageNotFoundException($languageId);
  22.         }
  23.         return $languages[$languageId]['code'];
  24.     }
  25.     /**
  26.      * @param array<string> $languageIds
  27.      */
  28.     public function getLocalesForLanguageIds(array $languageIds): array
  29.     {
  30.         $languages $this->getLanguages();
  31.         $requestedLanguages array_intersect_key($languagesarray_flip($languageIds));
  32.         return array_column($requestedLanguages'code''id');
  33.     }
  34.     public function reset(): void
  35.     {
  36.         $this->languages = [];
  37.     }
  38.     private function getLanguages(): array
  39.     {
  40.         if (\count($this->languages) === 0) {
  41.             $this->languages $this->resolveParentLanguages(
  42.                 $this->languageLoader->loadLanguages()
  43.             );
  44.         }
  45.         return $this->languages;
  46.     }
  47.     /**
  48.      * resolves the inherited languages codes, so we have a guaranteed language code for each language id
  49.      * we can't do it in the language loader as other places (e.g. DAL writes) expect that the translation code is unique
  50.      */
  51.     private function resolveParentLanguages(array $languages): array
  52.     {
  53.         foreach ($languages as &$language) {
  54.             if ($language['code'] !== null || $language['parentId'] === null) {
  55.                 continue;
  56.             }
  57.             $language['code'] = $languages[$language['parentId']]['code'] ?? null;
  58.         }
  59.         return $languages;
  60.     }
  61. }