|
1
|
|
|
<?php |
|
2
|
|
|
namespace PSFS\base\extension; |
|
3
|
|
|
|
|
4
|
|
|
use PSFS\base\Logger; |
|
5
|
|
|
use PSFS\base\Security; |
|
6
|
|
|
use PSFS\base\types\helpers\I18nHelper; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class CustomTranslateExtension |
|
10
|
|
|
* @package PSFS\base\extension |
|
11
|
|
|
*/ |
|
12
|
|
|
class CustomTranslateExtension extends \Twig_Extension { |
|
13
|
|
|
const CUSTOM_LOCALE_SESSION_KEY = '__PSFS_CUSTOM_LOCALE_KEY__'; |
|
14
|
|
|
|
|
15
|
|
|
protected $translations = []; |
|
16
|
|
|
protected $locale = 'es_ES'; |
|
17
|
|
|
|
|
18
|
1 |
|
public function __construct() |
|
19
|
|
|
{ |
|
20
|
1 |
|
$this->locale = I18nHelper::extractLocale('es_ES'); |
|
21
|
1 |
|
$custom_key = Security::getInstance()->getSessionKey(self::CUSTOM_LOCALE_SESSION_KEY); |
|
22
|
1 |
|
if(null !== $custom_key) { |
|
23
|
|
|
Logger::log('[' . self::class . '] Custom key detected: ' . $custom_key, LOG_INFO); |
|
24
|
|
|
$filename = implode(DIRECTORY_SEPARATOR, [LOCALE_DIR, 'custom', $custom_key, $this->locale . '.json']); |
|
25
|
|
|
if(file_exists($filename)) { |
|
26
|
|
|
Logger::log('[' . self::class . '] Custom locale detected: ' . $custom_key . ' [' . $this->locale . ']', LOG_INFO); |
|
|
|
|
|
|
27
|
|
|
$this->translations = json_decode(file_get_contents($filename), true); |
|
28
|
|
|
} |
|
29
|
|
|
} |
|
30
|
1 |
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritdoc} |
|
34
|
|
|
*/ |
|
35
|
1 |
|
public function getTokenParsers() |
|
36
|
|
|
{ |
|
37
|
1 |
|
return array(new \Twig_Extensions_TokenParser_Trans()); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* {@inheritdoc} |
|
42
|
|
|
*/ |
|
43
|
|
|
public function getFilters() |
|
44
|
|
|
{ |
|
45
|
|
|
return array( |
|
46
|
1 |
|
new \Twig_SimpleFilter('trans', function($message) { |
|
47
|
1 |
|
if(array_key_exists($message, $this->translations)) { |
|
48
|
|
|
return $this->translations[$message]; |
|
49
|
|
|
} else { |
|
50
|
1 |
|
return gettext($message); |
|
51
|
|
|
} |
|
52
|
1 |
|
}), |
|
53
|
|
|
); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* {@inheritdoc} |
|
58
|
|
|
*/ |
|
59
|
1 |
|
public function getName() |
|
60
|
|
|
{ |
|
61
|
1 |
|
return 'PSFSi18n'; |
|
62
|
|
|
} |
|
63
|
|
|
} |
Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.