1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Saxulum\Translation\Provider; |
4
|
|
|
|
5
|
|
|
use Pimple\Container; |
6
|
|
|
use Pimple\ServiceProviderInterface; |
7
|
|
|
use Symfony\Component\Finder\Finder; |
8
|
|
|
use Symfony\Component\Finder\SplFileInfo; |
9
|
|
|
use Symfony\Component\Translation\Loader\YamlFileLoader; |
10
|
|
|
use Symfony\Component\Translation\Translator; |
11
|
|
|
|
12
|
|
|
class TranslationProvider implements ServiceProviderInterface |
13
|
|
|
{ |
14
|
|
|
public function register(Container $container) |
15
|
|
|
{ |
16
|
|
|
$container['translation_cache'] = null; |
17
|
|
|
|
18
|
|
|
$container['translation_paths'] = function () { |
19
|
|
|
$paths = array(); |
20
|
|
|
|
21
|
|
|
return $paths; |
22
|
|
|
}; |
23
|
|
|
|
24
|
|
|
$container['translator'] = $container->extend('translator', |
25
|
|
|
function (Translator $translator) use ($container) { |
26
|
|
|
|
27
|
|
|
if (!is_null($container['translation_cache'])) { |
28
|
|
|
if (!is_null($container['translation_cache']) && !is_dir($container['translation_cache'])) { |
29
|
|
|
mkdir($container['translation_cache'], 0777, true); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$cacheFile = $container['translation_cache'] . '/saxulum-translation.php'; |
33
|
|
|
if ($container['debug'] || !file_exists($cacheFile)) { |
34
|
|
|
$translationMap = $container['translation_search'](); |
35
|
|
|
file_put_contents( |
36
|
|
|
$cacheFile, |
37
|
|
|
'<?php return ' . var_export($translationMap, true) . ';' |
38
|
|
|
); |
39
|
|
|
} else { |
40
|
|
|
$translationMap = require $cacheFile; |
41
|
|
|
} |
42
|
|
|
} else { |
43
|
|
|
$translationMap = $container['translation_search'](); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$translator->addLoader('yaml', new YamlFileLoader()); |
47
|
|
|
foreach ($translationMap as $translation) { |
48
|
|
|
$translator->addResource('yaml', $translation['path'], $translation['locale'], $translation['domain']); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $translator; |
52
|
|
|
} |
53
|
|
|
); |
54
|
|
|
|
55
|
|
|
$container['translation_search'] = $container->protect(function () use ($container) { |
56
|
|
|
$translationMap = array(); |
57
|
|
|
foreach ($container['translation_paths'] as $path) { |
58
|
|
|
foreach (Finder::create()->files()->name('*.yml')->in($path) as $file) { |
59
|
|
|
/** @var SplFileInfo $file */ |
60
|
|
|
$domainAndLocale = explode('.', $file->getBasename('.yml')); |
61
|
|
|
if (count($domainAndLocale) == 2) { |
62
|
|
|
$translationMap[] = array( |
63
|
|
|
'path' => $file->getPathname(), |
64
|
|
|
'locale' => $domainAndLocale[1], |
65
|
|
|
'domain' => $domainAndLocale[0] |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $translationMap; |
72
|
|
|
}); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|