Support module prefixing of locale resources

In preparation for upcoming changes, allow locale resources to have a module prefix added when they are loaded from a file.
This commit is contained in:
Toby Zerner 2016-11-28 11:28:10 +10:30
parent dd209b1747
commit 060745ecb7
4 changed files with 42 additions and 4 deletions

View File

@ -95,7 +95,7 @@ abstract class AbstractWebApp
*/
protected function getTranslationFilter()
{
return '/^[^\.]+\.(?:'.$this->getName().'|lib)\./';
return '/^.+(?:\.|::)(?:'.$this->getName().'|lib)\./';
}
/**

View File

@ -58,9 +58,11 @@ class LocaleManager
return isset($this->locales[$locale]);
}
public function addTranslations($locale, $file)
public function addTranslations($locale, $file, $module = null)
{
$this->translator->addResource('yaml', $file, $locale);
$prefix = $module ? $module.'::' : '';
$this->translator->addResource('prefixed_yaml', compact('file', 'prefix'), $locale);
}
public function addJsFile($locale, $js)

View File

@ -43,7 +43,7 @@ class LocaleServiceProvider extends AbstractServiceProvider
$translator = new Translator($defaultLocale, new MessageSelector());
$translator->setFallbackLocales([$defaultLocale, 'en']);
$translator->addLoader('yaml', new YamlFileLoader());
$translator->addLoader('prefixed_yaml', new PrefixedYamlFileLoader());
return $translator;
});

View File

@ -0,0 +1,36 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Locale;
use Symfony\Component\Translation\Loader\YamlFileLoader;
class PrefixedYamlFileLoader extends YamlFileLoader
{
/**
* {@inheritdoc}
*/
public function load($resource, $locale, $domain = 'messages')
{
$catalogue = parent::load($resource['file'], $locale, $domain);
if (! empty($resource['prefix'])) {
$messages = $catalogue->all($domain);
$prefixedKeys = array_map(function ($k) use ($resource) {
return $resource['prefix'].$k;
}, array_keys($messages));
$catalogue->replace(array_combine($prefixedKeys, $messages));
}
return $catalogue;
}
}