0e3dd06c5d39f551d873cf7e80cd88a704c7c3ee
[yaffs-website] / vendor / symfony / translation / Translator.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Translation;
13
14 use Symfony\Component\Translation\Loader\LoaderInterface;
15 use Symfony\Component\Translation\Exception\NotFoundResourceException;
16 use Symfony\Component\Config\ConfigCacheInterface;
17 use Symfony\Component\Config\ConfigCacheFactoryInterface;
18 use Symfony\Component\Config\ConfigCacheFactory;
19
20 /**
21  * Translator.
22  *
23  * @author Fabien Potencier <fabien@symfony.com>
24  */
25 class Translator implements TranslatorInterface, TranslatorBagInterface
26 {
27     /**
28      * @var MessageCatalogueInterface[]
29      */
30     protected $catalogues = array();
31
32     /**
33      * @var string
34      */
35     protected $locale;
36
37     /**
38      * @var array
39      */
40     private $fallbackLocales = array();
41
42     /**
43      * @var LoaderInterface[]
44      */
45     private $loaders = array();
46
47     /**
48      * @var array
49      */
50     private $resources = array();
51
52     /**
53      * @var MessageSelector
54      */
55     private $selector;
56
57     /**
58      * @var string
59      */
60     private $cacheDir;
61
62     /**
63      * @var bool
64      */
65     private $debug;
66
67     /**
68      * @var ConfigCacheFactoryInterface|null
69      */
70     private $configCacheFactory;
71
72     /**
73      * Constructor.
74      *
75      * @param string               $locale   The locale
76      * @param MessageSelector|null $selector The message selector for pluralization
77      * @param string|null          $cacheDir The directory to use for the cache
78      * @param bool                 $debug    Use cache in debug mode ?
79      *
80      * @throws \InvalidArgumentException If a locale contains invalid characters
81      */
82     public function __construct($locale, MessageSelector $selector = null, $cacheDir = null, $debug = false)
83     {
84         $this->setLocale($locale);
85         $this->selector = $selector ?: new MessageSelector();
86         $this->cacheDir = $cacheDir;
87         $this->debug = $debug;
88     }
89
90     /**
91      * Sets the ConfigCache factory to use.
92      *
93      * @param ConfigCacheFactoryInterface $configCacheFactory
94      */
95     public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
96     {
97         $this->configCacheFactory = $configCacheFactory;
98     }
99
100     /**
101      * Adds a Loader.
102      *
103      * @param string          $format The name of the loader (@see addResource())
104      * @param LoaderInterface $loader A LoaderInterface instance
105      */
106     public function addLoader($format, LoaderInterface $loader)
107     {
108         $this->loaders[$format] = $loader;
109     }
110
111     /**
112      * Adds a Resource.
113      *
114      * @param string $format   The name of the loader (@see addLoader())
115      * @param mixed  $resource The resource name
116      * @param string $locale   The locale
117      * @param string $domain   The domain
118      *
119      * @throws \InvalidArgumentException If the locale contains invalid characters
120      */
121     public function addResource($format, $resource, $locale, $domain = null)
122     {
123         if (null === $domain) {
124             $domain = 'messages';
125         }
126
127         $this->assertValidLocale($locale);
128
129         $this->resources[$locale][] = array($format, $resource, $domain);
130
131         if (in_array($locale, $this->fallbackLocales)) {
132             $this->catalogues = array();
133         } else {
134             unset($this->catalogues[$locale]);
135         }
136     }
137
138     /**
139      * {@inheritdoc}
140      */
141     public function setLocale($locale)
142     {
143         $this->assertValidLocale($locale);
144         $this->locale = $locale;
145     }
146
147     /**
148      * {@inheritdoc}
149      */
150     public function getLocale()
151     {
152         return $this->locale;
153     }
154
155     /**
156      * Sets the fallback locale(s).
157      *
158      * @param string|array $locales The fallback locale(s)
159      *
160      * @throws \InvalidArgumentException If a locale contains invalid characters
161      *
162      * @deprecated since version 2.3, to be removed in 3.0. Use setFallbackLocales() instead
163      */
164     public function setFallbackLocale($locales)
165     {
166         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the setFallbackLocales() method instead.', E_USER_DEPRECATED);
167
168         $this->setFallbackLocales(is_array($locales) ? $locales : array($locales));
169     }
170
171     /**
172      * Sets the fallback locales.
173      *
174      * @param array $locales The fallback locales
175      *
176      * @throws \InvalidArgumentException If a locale contains invalid characters
177      */
178     public function setFallbackLocales(array $locales)
179     {
180         // needed as the fallback locales are linked to the already loaded catalogues
181         $this->catalogues = array();
182
183         foreach ($locales as $locale) {
184             $this->assertValidLocale($locale);
185         }
186
187         $this->fallbackLocales = $locales;
188     }
189
190     /**
191      * Gets the fallback locales.
192      *
193      * @return array $locales The fallback locales
194      */
195     public function getFallbackLocales()
196     {
197         return $this->fallbackLocales;
198     }
199
200     /**
201      * {@inheritdoc}
202      */
203     public function trans($id, array $parameters = array(), $domain = null, $locale = null)
204     {
205         if (null === $domain) {
206             $domain = 'messages';
207         }
208
209         return strtr($this->getCatalogue($locale)->get((string) $id, $domain), $parameters);
210     }
211
212     /**
213      * {@inheritdoc}
214      */
215     public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
216     {
217         if (null === $domain) {
218             $domain = 'messages';
219         }
220
221         $id = (string) $id;
222         $catalogue = $this->getCatalogue($locale);
223         $locale = $catalogue->getLocale();
224         while (!$catalogue->defines($id, $domain)) {
225             if ($cat = $catalogue->getFallbackCatalogue()) {
226                 $catalogue = $cat;
227                 $locale = $catalogue->getLocale();
228             } else {
229                 break;
230             }
231         }
232
233         return strtr($this->selector->choose($catalogue->get($id, $domain), (int) $number, $locale), $parameters);
234     }
235
236     /**
237      * {@inheritdoc}
238      */
239     public function getCatalogue($locale = null)
240     {
241         if (null === $locale) {
242             $locale = $this->getLocale();
243         } else {
244             $this->assertValidLocale($locale);
245         }
246
247         if (!isset($this->catalogues[$locale])) {
248             $this->loadCatalogue($locale);
249         }
250
251         return $this->catalogues[$locale];
252     }
253
254     /**
255      * Gets the loaders.
256      *
257      * @return array LoaderInterface[]
258      */
259     protected function getLoaders()
260     {
261         return $this->loaders;
262     }
263
264     /**
265      * Collects all messages for the given locale.
266      *
267      * @param string|null $locale Locale of translations, by default is current locale
268      *
269      * @return array[array] indexed by catalog
270      *
271      * @deprecated since version 2.8, to be removed in 3.0. Use TranslatorBagInterface::getCatalogue() method instead.
272      */
273     public function getMessages($locale = null)
274     {
275         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Use TranslatorBagInterface::getCatalogue() method instead.', E_USER_DEPRECATED);
276
277         $catalogue = $this->getCatalogue($locale);
278         $messages = $catalogue->all();
279         while ($catalogue = $catalogue->getFallbackCatalogue()) {
280             $messages = array_replace_recursive($catalogue->all(), $messages);
281         }
282
283         return $messages;
284     }
285
286     /**
287      * @param string $locale
288      */
289     protected function loadCatalogue($locale)
290     {
291         if (null === $this->cacheDir) {
292             $this->initializeCatalogue($locale);
293         } else {
294             $this->initializeCacheCatalogue($locale);
295         }
296     }
297
298     /**
299      * @param string $locale
300      */
301     protected function initializeCatalogue($locale)
302     {
303         $this->assertValidLocale($locale);
304
305         try {
306             $this->doLoadCatalogue($locale);
307         } catch (NotFoundResourceException $e) {
308             if (!$this->computeFallbackLocales($locale)) {
309                 throw $e;
310             }
311         }
312         $this->loadFallbackCatalogues($locale);
313     }
314
315     /**
316      * @param string $locale
317      */
318     private function initializeCacheCatalogue($locale)
319     {
320         if (isset($this->catalogues[$locale])) {
321             /* Catalogue already initialized. */
322             return;
323         }
324
325         $this->assertValidLocale($locale);
326         $self = $this; // required for PHP 5.3 where "$this" cannot be use()d in anonymous functions. Change in Symfony 3.0.
327         $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
328             function (ConfigCacheInterface $cache) use ($self, $locale) {
329                 $self->dumpCatalogue($locale, $cache);
330             }
331         );
332
333         if (isset($this->catalogues[$locale])) {
334             /* Catalogue has been initialized as it was written out to cache. */
335             return;
336         }
337
338         /* Read catalogue from cache. */
339         $this->catalogues[$locale] = include $cache->getPath();
340     }
341
342     /**
343      * This method is public because it needs to be callable from a closure in PHP 5.3. It should be made protected (or even private, if possible) in 3.0.
344      *
345      * @internal
346      */
347     public function dumpCatalogue($locale, ConfigCacheInterface $cache)
348     {
349         $this->initializeCatalogue($locale);
350         $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
351
352         $content = sprintf(<<<EOF
353 <?php
354
355 use Symfony\Component\Translation\MessageCatalogue;
356
357 \$catalogue = new MessageCatalogue('%s', %s);
358
359 %s
360 return \$catalogue;
361
362 EOF
363             ,
364             $locale,
365             var_export($this->catalogues[$locale]->all(), true),
366             $fallbackContent
367         );
368
369         $cache->write($content, $this->catalogues[$locale]->getResources());
370     }
371
372     private function getFallbackContent(MessageCatalogue $catalogue)
373     {
374         $fallbackContent = '';
375         $current = '';
376         $replacementPattern = '/[^a-z0-9_]/i';
377         $fallbackCatalogue = $catalogue->getFallbackCatalogue();
378         while ($fallbackCatalogue) {
379             $fallback = $fallbackCatalogue->getLocale();
380             $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
381             $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
382
383             $fallbackContent .= sprintf(<<<'EOF'
384 $catalogue%s = new MessageCatalogue('%s', %s);
385 $catalogue%s->addFallbackCatalogue($catalogue%s);
386
387 EOF
388                 ,
389                 $fallbackSuffix,
390                 $fallback,
391                 var_export($fallbackCatalogue->all(), true),
392                 $currentSuffix,
393                 $fallbackSuffix
394             );
395             $current = $fallbackCatalogue->getLocale();
396             $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
397         }
398
399         return $fallbackContent;
400     }
401
402     private function getCatalogueCachePath($locale)
403     {
404         return $this->cacheDir.'/catalogue.'.$locale.'.'.sha1(serialize($this->fallbackLocales)).'.php';
405     }
406
407     private function doLoadCatalogue($locale)
408     {
409         $this->catalogues[$locale] = new MessageCatalogue($locale);
410
411         if (isset($this->resources[$locale])) {
412             foreach ($this->resources[$locale] as $resource) {
413                 if (!isset($this->loaders[$resource[0]])) {
414                     throw new \RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
415                 }
416                 $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
417             }
418         }
419     }
420
421     private function loadFallbackCatalogues($locale)
422     {
423         $current = $this->catalogues[$locale];
424
425         foreach ($this->computeFallbackLocales($locale) as $fallback) {
426             if (!isset($this->catalogues[$fallback])) {
427                 $this->initializeCatalogue($fallback);
428             }
429
430             $fallbackCatalogue = new MessageCatalogue($fallback, $this->catalogues[$fallback]->all());
431             foreach ($this->catalogues[$fallback]->getResources() as $resource) {
432                 $fallbackCatalogue->addResource($resource);
433             }
434             $current->addFallbackCatalogue($fallbackCatalogue);
435             $current = $fallbackCatalogue;
436         }
437     }
438
439     protected function computeFallbackLocales($locale)
440     {
441         $locales = array();
442         foreach ($this->fallbackLocales as $fallback) {
443             if ($fallback === $locale) {
444                 continue;
445             }
446
447             $locales[] = $fallback;
448         }
449
450         if (strrchr($locale, '_') !== false) {
451             array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
452         }
453
454         return array_unique($locales);
455     }
456
457     /**
458      * Asserts that the locale is valid, throws an Exception if not.
459      *
460      * @param string $locale Locale to tests
461      *
462      * @throws \InvalidArgumentException If the locale contains invalid characters
463      */
464     protected function assertValidLocale($locale)
465     {
466         if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
467             throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
468         }
469     }
470
471     /**
472      * Provides the ConfigCache factory implementation, falling back to a
473      * default implementation if necessary.
474      *
475      * @return ConfigCacheFactoryInterface $configCacheFactory
476      */
477     private function getConfigCacheFactory()
478     {
479         if (!$this->configCacheFactory) {
480             $this->configCacheFactory = new ConfigCacheFactory($this->debug);
481         }
482
483         return $this->configCacheFactory;
484     }
485 }