5 use Symfony\Component\Translation
;
7 class Translator
extends Translation\Translator
10 * Singleton for Translator.
14 protected static $singleton;
17 * List of custom localized messages.
21 protected static $messages = array();
24 * Return a singleton instance of Translator.
26 * @param string|null $locale optional initial locale ("en" - english by default)
30 public static function get($locale = null)
32 if (static::$singleton === null) {
33 static::$singleton = new static($locale ?
: 'en');
36 return static::$singleton;
39 public function __construct($locale, Translation\Formatter\MessageFormatterInterface
$formatter = null, $cacheDir = null, $debug = false)
41 $this->addLoader('array', new Translation\Loader\
ArrayLoader());
42 parent
::__construct($locale, $formatter, $cacheDir, $debug);
46 * Reset messages of a locale (all locale if no locale passed).
47 * Remove custom messages and reload initial messages from matching
48 * file in Lang directory.
50 * @param string|null $locale
54 public function resetMessages($locale = null)
56 if ($locale === null) {
57 static::$messages = array();
62 if (file_exists($filename = __DIR__
.'/Lang/'.$locale.'.php')) {
63 static::$messages[$locale] = require $filename;
64 $this->addResource('array', static::$messages[$locale], $locale);
73 * Init messages language from matching file in Lang directory.
75 * @param string $locale
79 protected function loadMessagesFromFile($locale)
81 if (isset(static::$messages[$locale])) {
85 return $this->resetMessages($locale);
89 * Set messages of a locale and take file first if present.
91 * @param string $locale
92 * @param array $messages
96 public function setMessages($locale, $messages)
98 $this->loadMessagesFromFile($locale);
99 $this->addResource('array', $messages, $locale);
100 static::$messages[$locale] = array_merge(
101 isset(static::$messages[$locale]) ?
static::$messages[$locale] : array(),
109 * Get messages of a locale, if none given, return all the
112 * @param string|null $locale
116 public function getMessages($locale = null)
118 return $locale === null ?
static::$messages : static::$messages[$locale];
122 * Set the current translator locale and indicate if the source locale file exists
124 * @param string $locale locale ex. en
128 public function setLocale($locale)
130 $locale = preg_replace_callback('/[-_]([a-z]{2,})/', function ($matches) {
131 // _2-letters is a region, _3+-letters is a variant
132 return '_'.call_user_func(strlen($matches[1]) > 2 ?
'ucfirst' : 'strtoupper', $matches[1]);
133 }, strtolower($locale));
135 if ($this->loadMessagesFromFile($locale)) {
136 parent
::setLocale($locale);