-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathL10n.php
122 lines (101 loc) · 2.94 KB
/
L10n.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
120
121
122
<?php
namespace Sergo\L10n;
use Sergo\L10n\Config\Settings;
use Sergo\L10n\Repositories\FileRepository;
use Sergo\L10n\Repositories\MysqlRepository;
// TODO implement parse "this.ololo"
class L10n
{
/**
* @param array
*/
protected $allowed_repositories = ['mysql', 'files'];
/**
* @var array
*/
protected $default_settings = [
'repository' => 'mysql',
'locale' => 'uk',
'separator' => '.', // actual only for FILES repository
'var_separator_left' => '{',
'var_separator_right' => '}',
];
/**
* @var array
*/
protected $settings = [];
/**
* @var array
*/
protected static $cache = [];
protected $repository;
/**
* @param array $settings
*
* @throws \Exception
*/
public function __construct(array $settings) {
$this->settings = array_merge($this->default_settings, $settings);
Settings::getInstance()->setSettings($this->settings);
$repository = $this->settings['repository'];
if ($this->isCorrectRepository($repository)) {
switch (true) {
case ($repository === 'mysql'): {
$this->repository = new MysqlRepository($this->settings['credentials'], $this->settings['table_name']);
} break;
case ($repository === 'files'): {
$this->repository = new FileRepository($this->settings['files_path']);
} break;
}
} else {
throw new \Exception("Undefined repository");
}
}
/**
* @param string $key
* @param array $params
*
* @return array|string
*/
public function get($key, $params = array()) {
$result = $this->repository->get($key);
return (!empty($params) && is_array($params)) ? $this->parseParams($result, $params) : $result;
}
/**
* @param array $keys
* @param array $params
*
* @return array
*/
public function getFew(array $keys, $params = array()) {
$result = $this->repository->getFew($keys);
foreach($result as $key => &$value) {
if (isset($params[$key])) {
$value = $this->parseParams($value, $params[$key]);
}
}
return $result;
}
/**
* @param string $string
* @param array $params
*
* @return mixed
*/
public function parseParams($string, $params) {
$from = array_keys($params);
$from = array_map(function($val) {
return $this->settings['var_separator_left'] . $val . $this->settings['var_separator_right'];
}, $from);
$to = array_values($params);
return str_replace($from, $to, $string);
}
/**
* @param $repository
*
* @return bool
*/
protected function isCorrectRepository($repository) {
return in_array($repository, $this->allowed_repositories);
}
}