1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Grido (https://github.com/o5/grido) |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2011 Petr Bugyík (http://petr.bugyik.cz) |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view |
9
|
|
|
* the file LICENSE.md that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Grido\Translations; |
13
|
|
|
|
14
|
|
|
use Grido\Exception; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Simple file translator. |
18
|
|
|
* |
19
|
|
|
* @package Grido |
20
|
|
|
* @subpackage Translations |
21
|
|
|
* @author Petr Bugyík |
22
|
|
|
*/ |
23
|
1 |
|
class FileTranslator implements \Nette\Localization\ITranslator |
24
|
|
|
{ |
25
|
|
|
use \Nette\SmartObject; |
26
|
|
|
|
27
|
|
|
/** @var array */ |
28
|
|
|
protected $translations = []; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param string $lang |
32
|
|
|
* @param array $translations |
33
|
|
|
*/ |
34
|
1 |
|
public function __construct($lang = 'en', array $translations = []) |
35
|
1 |
|
{ |
36
|
1 |
|
$translations = $translations + $this->getTranslationsFromFile($lang); |
37
|
|
|
$this->translations = $translations; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Sets language of translation. |
42
|
|
|
* @param string $lang |
43
|
|
|
*/ |
44
|
1 |
|
public function setLang($lang) |
45
|
1 |
|
{ |
46
|
|
|
$this->translations = $this->getTranslationsFromFile($lang); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $lang |
51
|
|
|
* @throws Exception |
52
|
|
|
* @return array |
53
|
|
|
*/ |
54
|
1 |
|
protected function getTranslationsFromFile($lang) |
55
|
1 |
|
{ |
56
|
1 |
|
$filename = __DIR__ . "/$lang.php"; |
57
|
|
|
if (!file_exists($filename)) { |
58
|
|
|
throw new Exception("Translations for language '$lang' not found."); |
59
|
1 |
|
} |
60
|
|
|
|
61
|
|
|
return include ($filename); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/************************* interface \Nette\Localization\ITranslator **************************/ |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string $message |
68
|
|
|
* @param ...$parameters |
69
|
|
|
* @return string |
70
|
|
|
*/ |
71
|
1 |
|
public function translate($message, ...$parameters): string |
72
|
1 |
|
{ |
73
|
1 |
|
return isset($this->translations[$message]) |
74
|
|
|
? $this->translations[$message] |
75
|
|
|
: ($message ?? ''); |
76
|
1 |
|
} |
77
|
|
|
} |
78
|
|
|
|