/
i18n.php
119 lines (106 loc) · 2.31 KB
/
i18n.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/**
* php-i18n-yaml
*
* I18N class for translating text to any language
* Uses YAML files
*
* Usage: I18N::t("user.name") # => "Karl Metum"
* In the above example "name" is nested under "user"
*
* Make sure that the following constants are set in
* your environment somehow:
*
* - DEFAULT_LOCALE = ""
* - DIR_LOCALE = "" # full path to your locales
*
* @author Karl Metum <karlo.m@gmail.com>
* @link https://github.com/karlingen/php-i18n-yaml
*/
class I18N
{
/**
* Holds the current locale
*/
private $locale;
/**
* Holds the character which terms are seperated by
*/
private $term_separator = ".";
/**
* Main construct
* @param locale
*/
public function __construct($locale=null)
{
$this->set_locale($locale);
}
/**
* Sets the current locale
*/
private function set_locale($locale=null)
{
$locale=is_null($locale) ? DEFAULT_LOCALE : $locale;
$this->locale = $locale;
}
/**
* Gets current locale
*/
private function get_locale()
{
return $this->locale;
}
/**
* Translates given term
*/
public function _translate($term)
{
$path=$this->build_file_path();
$yaml_parsed=yaml_parse_file($path);
return $this->find($term, $yaml_parsed);
}
/**
* Finds given term inside given yaml-parsed array
* @param string, the text to examine and look for
* @param array, yaml parsed data
*/
private function find($term, Array $yaml_data)
{
$locale=$this->get_locale();
if(!empty($yaml_data[$locale]))
{
$yaml_data_last=$yaml_data[$locale];
$terms=explode($this->term_separator, $term);
foreach($terms as $keyword)
{
if(empty($yaml_data_last[$keyword]))
return "Translation missing for {$locale}#{$term}";
$yaml_data_last=$yaml_data_last[$keyword];
}
return $yaml_data_last;
}
return "Translation missing for {$locale}";
}
private function build_file_path()
{
return DIR_LOCALE.$this->get_locale().".yml";
}
/**
* Translates given term
* @param string, the translation term
* @param string, (optional) the language which the term
* should be translated into.
*/
public static function translate($term,$locale=null)
{
$i18n = new self($locale);
return $i18n->_translate($term);
}
/**
* Alias for @translate
*/
public static function t($term,$locale=null)
{
return self::translate($term,$locale);
}
}