1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* a way to load dynamically added resources files to Translator |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace Graviton\I18nBundle\Translator; |
7
|
|
|
|
8
|
|
|
use Graviton\I18nBundle\Service\I18nCacheUtils; |
9
|
|
|
use Symfony\Component\Translation\TranslatorInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> |
13
|
|
|
* @license http://opensource.org/licenses/gpl-license.php GNU Public License |
14
|
|
|
* @link http://swisscom.ch |
15
|
|
|
*/ |
16
|
|
|
class TranslatorFactory |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* factory method, creates a translator |
21
|
|
|
* |
22
|
|
|
* @param TranslatorInterface $translator translator |
23
|
|
|
* @param I18nCacheUtils $cacheUtils cache utils |
24
|
|
|
* |
25
|
|
|
* @return TranslatorInterface translator |
26
|
|
|
*/ |
27
|
|
|
public static function createTranslator(TranslatorInterface $translator, I18nCacheUtils $cacheUtils) |
28
|
|
|
{ |
29
|
|
|
return self::addResourceFiles($translator, $cacheUtils->getResources([])); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* as we cannot add resources files directly (the function from where i lifted this is private), |
34
|
|
|
* we copied this here and add it as Translator would (and does) |
35
|
|
|
* |
36
|
|
|
* @param TranslatorInterface $translator translator |
37
|
|
|
* @param array $resources added resources |
38
|
|
|
* |
39
|
|
|
* @return TranslatorInterface translator |
40
|
|
|
*/ |
41
|
|
|
private static function addResourceFiles(TranslatorInterface $translator, array $resources) |
42
|
|
|
{ |
43
|
|
|
foreach ($resources as $locale => $files) { |
44
|
|
|
foreach ($files as $key => $file) { |
45
|
|
|
// filename is domain.locale.format |
46
|
|
|
list($domain, $locale, $format) = explode('.', basename($file), 3); |
47
|
|
|
$translator->addResource($format, $file, $locale, $domain); |
|
|
|
|
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $translator; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: