setLocale($locale); } /** * Setups the translator */ public function configureDirectory(string $isoNumber, string $directory): void { if (!preg_match(LocaleInterface::LOCALE_EXPRESSION, $this->locale, $matches)) { throw new DomainException("Invalid locale \"{$this->locale}\""); } $locale = (object) [ 'language' => $matches['language'], 'country' => $matches['country'] ?? null, 'script' => $matches['script'] ?? null ]; $locales = [$this->locale, ...($locale->script ? [$locale->language . '@' . $locale->script] : []), $locale->language]; // Attempts to find the best locale foreach ($locales as $locale) { $path = "{$directory}/{$locale}/LC_MESSAGES/{$isoNumber}.mo"; if (file_exists($path)) { // Check if it's installed before caching the ISO codes (huge dataset), just to avoid a slow installation page $loader = fn () => Translator::createFromTranslationsArray(LocaleFile::loadArray($path, Application::isInstalled())); $key = __METHOD__ . static::MAX_CACHE_LIFETIME . $path . filemtime($path); $expiration = DateInterval::createFromDateString(static::MAX_CACHE_LIFETIME); $this->translator = Application::isInstalled() ? Cache::remember($key, $expiration, $loader) : $loader(); break; } } } /** * Setup the driver locale */ public function setLocale(string $locale): void { $this->locale = $locale; } /** * Attempts to translate an entry */ public function translate(string $isoNumber, string $message): string { return $this->translator?->getSingular($message) ?: $message; } }