1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Foo\Translate; |
6
|
|
|
|
7
|
|
|
use Opulence\Cache\ICacheBridge; |
8
|
|
|
|
9
|
|
|
class Loader |
10
|
|
|
{ |
11
|
|
|
const CACHE_TEMPLATE = 'foo-translate-%s'; |
12
|
|
|
|
13
|
|
|
const LIFETIME = 1000000; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
protected $directory; |
17
|
|
|
|
18
|
|
|
/** @var ICacheBridge */ |
19
|
|
|
protected $cacheBridge; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Translator constructor. |
23
|
|
|
* |
24
|
|
|
* @param string $directory |
25
|
|
|
* @param ICacheBridge|null $cacheBridge |
26
|
|
|
*/ |
27
|
4 |
|
public function __construct(string $directory, ICacheBridge $cacheBridge = null) |
28
|
|
|
{ |
29
|
4 |
|
$this->directory = $directory; |
30
|
4 |
|
$this->cacheBridge = $cacheBridge; |
31
|
4 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param string $lang |
35
|
|
|
* |
36
|
|
|
* @return array |
37
|
|
|
*/ |
38
|
2 |
|
public function loadTranslations(string $lang): array |
39
|
|
|
{ |
40
|
2 |
|
$cacheKey = $this->getCacheKey($lang); |
41
|
|
|
|
42
|
2 |
|
if (null !== $this->cacheBridge && $this->cacheBridge->has($cacheKey)) { |
43
|
|
|
return $this->cacheBridge->get($cacheKey); |
44
|
|
|
} |
45
|
|
|
|
46
|
2 |
|
$translations = $this->loadTranslationsFromFiles($lang); |
47
|
|
|
|
48
|
2 |
|
if (null != $this->cacheBridge) { |
49
|
1 |
|
$this->cacheBridge->set($cacheKey, $translations, static::LIFETIME); |
50
|
|
|
} |
51
|
|
|
|
52
|
2 |
|
return $translations; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $lang |
57
|
|
|
* |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
2 |
|
protected function getCacheKey(string $lang): string |
61
|
|
|
{ |
62
|
2 |
|
return sprintf(static::CACHE_TEMPLATE, $lang); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $lang |
67
|
|
|
* |
68
|
|
|
* @return array |
69
|
|
|
*/ |
70
|
2 |
|
protected function loadTranslationsFromFiles(string $lang): array |
71
|
|
|
{ |
72
|
2 |
|
$dir = sprintf('%s/%s', $this->directory, $lang); |
73
|
|
|
|
74
|
2 |
|
if (!is_dir($dir)) { |
75
|
2 |
|
return []; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$translations = []; |
79
|
|
|
foreach (scandir($dir) as $file) { |
80
|
|
|
// Skip non-PHP files |
81
|
|
|
if (strlen($file) < 4 || substr($file, -4) !== '.php') { |
82
|
|
|
continue; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
$content = require $dir . $file; |
86
|
|
|
$namespace = substr($file, 0, -4); |
87
|
|
|
|
88
|
|
|
$translations[$lang][$namespace] = $content; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return $translations; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|