1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Erykai\Translate; |
4
|
|
|
|
5
|
|
|
use stdClass; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class translate remote all languages |
9
|
|
|
*/ |
10
|
|
|
class Translate extends Resource |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param object $data |
14
|
|
|
* @return $this |
15
|
|
|
*/ |
16
|
|
|
public function data(object $data): static |
17
|
|
|
{ |
18
|
|
|
if(!isset($data->dynamic)){ |
19
|
|
|
$data->dynamic = ""; |
20
|
|
|
} |
21
|
|
|
$this->setDynamic($data->dynamic); |
22
|
|
|
$data->text = str_replace($this->getDynamic(),"<#>", $data->text); |
23
|
|
|
|
24
|
|
|
$this->setData($data); |
25
|
|
|
return $this; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param ?string $lang |
30
|
|
|
* @return $this |
31
|
|
|
* detect language if not declare in target or const TRANSLATE_DEFAULT |
32
|
|
|
*/ |
33
|
|
|
public function target(?string $lang = null, string $module = null, ?string $keyArray = null): static |
34
|
|
|
{ |
35
|
|
|
$this->lang($lang); |
36
|
|
|
$this->dir($module); |
37
|
|
|
$this->file($module, $keyArray); |
38
|
|
|
$this->setResponse(); |
39
|
|
|
return $this; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string|null $lang |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
|
|
public function lang(?string $lang = null): string |
47
|
|
|
{ |
48
|
|
|
$this->setTarget('en'); |
49
|
|
|
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { |
50
|
|
|
[$l] = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']); |
51
|
|
|
$this->setTarget($l); |
52
|
|
|
} |
53
|
|
|
if(TRANSLATE_DEFAULT){ |
54
|
|
|
$this->setTarget(TRANSLATE_DEFAULT); |
55
|
|
|
} |
56
|
|
|
if ($lang) { |
57
|
|
|
$this->setTarget($lang); |
58
|
|
|
} |
59
|
|
|
return $this->getTarget(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param $messages |
64
|
|
|
* @param $translate |
65
|
|
|
* @param $filenameWithoutExtension |
66
|
|
|
* @param string $parentKey |
67
|
|
|
* @param string $target |
68
|
|
|
* @return void |
69
|
|
|
*/ |
70
|
|
|
public function processMessages($messages, $translate, $filenameWithoutExtension, string $parentKey = '', string $target = TRANSLATE_DEFAULT): void |
71
|
|
|
{ |
72
|
|
|
foreach ($messages as $key => $message) { |
73
|
|
|
$fullKey = $parentKey ? $parentKey . '.' . $key : $key; |
74
|
|
|
if (is_array($message)) { |
75
|
|
|
$this->processMessages($message, $translate, $filenameWithoutExtension, $fullKey, $target); |
76
|
|
|
} else { |
77
|
|
|
$data = new stdClass(); |
78
|
|
|
$data->file = $filenameWithoutExtension; |
79
|
|
|
$data->text = $message; |
80
|
|
|
$translate->data($data)->target($target, keyArray: $fullKey)->response(); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @return object |
87
|
|
|
*/ |
88
|
|
|
public function response(): object |
89
|
|
|
{ |
90
|
|
|
return $this->getResponse(); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
} |