Skip to content

Commit 42449db

Browse files
authored
Create Lang.php
1 parent 99e8147 commit 42449db

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

src/Locales/Lang.php

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
<?php
2+
/*
3+
the project created by @wizardloop
4+
*/
5+
namespace JewishPulse\Locales;
6+
7+
use Amp\File;
8+
use function Amp\File\write;
9+
use function Amp\File\read;
10+
use function Amp\File\exists;
11+
use function Amp\File\mkdir;
12+
13+
class Lang
14+
{
15+
private object $context;
16+
public function __construct(object $context) {
17+
$this->context = $context;
18+
}
19+
20+
public function getUserLang(int $senderId): string {
21+
try {
22+
$path = __DIR__ . "/../data/$senderId/lang.txt";
23+
24+
if (file_exists($path)) {
25+
return trim(read($path));
26+
} else {
27+
return 'he';
28+
}
29+
} catch (\Throwable $e) {
30+
return 'he';
31+
}
32+
}
33+
34+
function loadTranslations(string $lang): array {
35+
$path = __DIR__ . "/$lang.json";
36+
if (!file_exists($path)) {
37+
$path = __DIR__ . "/he.json";
38+
}
39+
return json_decode(read($path), true);
40+
}
41+
42+
function getAvailableLanguages(): array {
43+
$files = glob(__DIR__ . "/*.json");
44+
$langs = [];
45+
foreach ($files as $file) {
46+
$code = basename($file, '.json');
47+
$translations = json_decode(file_get_contents($file), true);
48+
$langs[] = [
49+
'code' => $code,
50+
'name' => $translations['language_name'] ?? strtoupper($code),
51+
'emoji' => $translations['language_flag'] ?? '🏳️'
52+
];
53+
}
54+
return $langs;
55+
}
56+
57+
function getLanguageButtons(): array {
58+
$settings_button_back_text = '🔙';
59+
$settings_button_back_data = 'SettingsMenu';
60+
61+
$langs = $this->getAvailableLanguages();
62+
63+
$bot_API_markup = [];
64+
65+
foreach ($langs as $lang) {
66+
$bot_API_markup[] = [
67+
'text' => $lang['emoji'] . ' ' . $lang['name'],
68+
'callback_data' => "setlang:" . $lang['code']
69+
];
70+
}
71+
72+
$keyboard = [];
73+
$row = [];
74+
75+
foreach ($bot_API_markup as $button) {
76+
$row[] = $button;
77+
if (count($row) == 2) {
78+
$keyboard[] = $row;
79+
$row = [];
80+
}
81+
}
82+
83+
if (count($row) > 0) {
84+
$keyboard[] = $row;
85+
}
86+
87+
$keyboard[] = [
88+
['text' => $settings_button_back_text, 'callback_data' => $settings_button_back_data]
89+
];
90+
91+
return [
92+
'inline_keyboard' => $keyboard
93+
];
94+
}
95+
96+
public function setUserLang(int $senderId, string $lang): bool {
97+
try {
98+
$dir = __DIR__ . "/../data/$senderId";
99+
$path = $dir . "/lang.txt";
100+
101+
if (!file_exists($dir)) {
102+
mkdir($dir, 0777, true);
103+
}
104+
105+
return file_put_contents($path, $lang) !== false;
106+
} catch (\Throwable $e) {
107+
return false;
108+
}
109+
}
110+
111+
}

0 commit comments

Comments
 (0)