Skip to main content

pakem/core/i18n/
manager.rs

1use serde_json::Value;
2use std::collections::HashMap;
3use std::fs;
4use std::path::Path;
5use std::sync::RwLock;
6use tracing::{error, warn};
7
8pub struct LangManager {
9    /// Cache untuk menyimpan terjemahan yang sudah dimuat.
10    /// Struktur: locale -> group -> key -> value
11    translations: RwLock<HashMap<String, HashMap<String, Value>>>,
12    default_locale: String,
13}
14
15impl LangManager {
16    pub fn new(default_locale: String) -> Self {
17        Self {
18            translations: RwLock::new(HashMap::new()),
19            default_locale,
20        }
21    }
22
23    /// Mendapatkan terjemahan berdasarkan key (format: "group.key").
24    pub fn get(&self, locale: &str, key: &str, params: HashMap<String, String>) -> String {
25        let parts: Vec<&str> = key.splitn(2, '.').collect();
26        if parts.len() < 2 {
27            return key.to_string();
28        }
29
30        let group = parts[0];
31        let item_key = parts[1];
32
33        // Pastikan locale dimuat
34        self.ensure_loaded(locale, group);
35
36        let translations = self.translations.read().unwrap();
37        if let Some(group_data) = translations.get(locale).and_then(|g| g.get(group)) {
38            if let Some(value) = self.resolve_key(group_data, item_key) {
39                return self.replace_params(value, params);
40            }
41        }
42
43        // Fallback ke default locale jika berbeda
44        if locale != self.default_locale {
45            return self.get(&self.default_locale, key, params);
46        }
47
48        key.to_string()
49    }
50
51    /// Memuat file JSON terjemahan jika belum ada di cache.
52    fn ensure_loaded(&self, locale: &str, group: &str) {
53        {
54            let translations = self.translations.read().unwrap();
55            if translations.contains_key(locale)
56                && translations.get(locale).unwrap().contains_key(group)
57            {
58                return;
59            }
60        }
61
62        let path = format!("lang/{}/{}.json", locale, group);
63        if !Path::new(&path).exists() {
64            return;
65        }
66
67        match fs::read_to_string(&path) {
68            Ok(content) => match serde_json::from_str::<Value>(&content) {
69                Ok(value) => {
70                    let mut translations = self.translations.write().unwrap();
71                    translations
72                        .entry(locale.to_string())
73                        .or_insert_with(HashMap::new)
74                        .insert(group.to_string(), value);
75                }
76                Err(e) => error!("Gagal parse JSON terjemahan {}: {}", path, e),
77            },
78            Err(e) => warn!("Gagal membaca file terjemahan {}: {}", path, e),
79        }
80    }
81
82    /// Mencari value dalam JSON object menggunakan dot notation (misal: "auth.login.failed").
83    fn resolve_key(&self, data: &Value, key: &str) -> Option<String> {
84        let mut current = data;
85        for part in key.split('.') {
86            current = current.get(part)?;
87        }
88        current.as_str().map(|s| s.to_string())
89    }
90
91    /// Mengganti placeholder :name dengan value dari params.
92    fn replace_params(&self, text: String, params: HashMap<String, String>) -> String {
93        let mut result = text;
94        for (key, value) in params {
95            result = result.replace(&format!(":{}", key), &value);
96        }
97        result
98    }
99}