#![warn(missing_docs)]
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, OnceLock};
use indexmap::IndexMap;
use php_std::Value;
use php_std::json::{self, Flags};
use php_std::types::KeyRef;
#[cfg(doctest)]
#[doc = include_str!("../guide.md")]
pub struct GettingStarted;
pub const DEFAULT_DYNAMIC_KEY: &str = "[[defaultDynamicKey]]";
type Hasher = foldhash::fast::RandomState;
pub type Translations = IndexMap<String, String, Hasher>;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error("{0}")]
Exception(String),
#[error("{0}")]
Type(String),
#[error("{0}")]
Unsupported(String),
}
impl Error {
pub fn php_class(&self) -> &'static str {
match self {
Error::Exception(_) | Error::Unsupported(_) => "Exception",
Error::Type(_) => "TypeError",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Missing<'a> {
#[default]
Key,
Text(&'a str),
Null,
}
#[derive(Debug, Clone)]
enum Language {
Texts(Translations),
Json(Arc<Json>),
Unusable(&'static str),
}
impl PartialEq for Language {
fn eq(&self, other: &Self) -> bool {
match (self.resolve(), other.resolve()) {
(Ok(a), Ok(b)) => a == b,
(Err(a), Err(b)) => a == b,
_ => false,
}
}
}
impl Language {
fn resolve(&self) -> Result<&Translations, &'static str> {
match self {
Language::Texts(texts) => Ok(texts),
Language::Json(json) => Ok(json.texts()),
Language::Unusable(given) => Err(given),
}
}
}
#[derive(Debug)]
struct Json {
text: Arc<[u8]>,
texts: OnceLock<Translations>,
}
impl Json {
fn texts(&self) -> &Translations {
self.texts.get_or_init(|| {
serde_json::from_slice(&self.text).expect("checked to be a JSON object of strings when it was registered")
})
}
}
fn is_object_of_strings(json: &[u8]) -> bool {
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
struct AnyString;
impl<'de> Deserialize<'de> for AnyString {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = AnyString;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: de::Error>(self, _: &str) -> Result<AnyString, E> {
Ok(AnyString)
}
}
deserializer.deserialize_string(V)
}
}
struct Object;
impl<'de> Deserialize<'de> for Object {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl<'de> Visitor<'de> for V {
type Value = Object;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("an object of strings")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Object, A::Error> {
while map.next_entry::<AnyString, AnyString>()?.is_some() {}
Ok(Object)
}
}
deserializer.deserialize_map(V)
}
}
serde_json::from_slice::<Object>(json).is_ok()
}
#[derive(Debug, Clone)]
pub struct Languages {
languages: IndexMap<String, Language, Hasher>,
exceptions: bool,
files: HashMap<Arc<[u8]>, Arc<Json>, Hasher>,
}
impl PartialEq for Languages {
fn eq(&self, other: &Self) -> bool {
self.exceptions == other.exceptions && self.languages == other.languages
}
}
impl Default for Languages {
fn default() -> Self {
Self::new()
}
}
impl Languages {
pub fn new() -> Self {
Self { languages: IndexMap::default(), exceptions: true, files: HashMap::default() }
}
pub fn exceptions(&self) -> bool {
self.exceptions
}
pub fn set_exceptions(&mut self, on: bool) {
self.exceptions = on;
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.languages.keys().map(String::as_str)
}
pub fn contains(&self, name: &str) -> bool {
self.languages.contains_key(name)
}
pub fn insert(&mut self, name: impl Into<String>, translations: Translations) {
self.languages.insert(name.into(), Language::Texts(translations));
}
pub fn load(&mut self, name: impl Into<String>, path: &Path) -> Result<(), Error> {
if self.exceptions && std::fs::metadata(path).is_err() {
return Err(Error::Exception("Translation file not found.".into()));
}
let content = std::fs::read(path).unwrap_or_default();
self.insert_json(name, &content)
}
pub fn insert_json(&mut self, name: impl Into<String>, json: &[u8]) -> Result<(), Error> {
if is_object_of_strings(json) {
let file = match self.files.get(json) {
Some(file) => Arc::clone(file),
None => {
let text: Arc<[u8]> = json.into();
let file = Arc::new(Json { text: Arc::clone(&text), texts: OnceLock::new() });
self.files.insert(text, Arc::clone(&file));
file
}
};
self.languages.insert(name.into(), Language::Json(file));
return Ok(());
}
let language = match json::decode(json, Some(true), 512, Flags::NONE) {
Err(_) | Ok(Value::Null) => Language::Unusable("null"),
Ok(Value::Bool(true)) => Language::Unusable("true"),
Ok(Value::Bool(false)) => Language::Unusable("false"),
Ok(Value::Int(_)) => Language::Unusable("int"),
Ok(Value::Float(_)) => Language::Unusable("float"),
Ok(Value::Str(_)) => Language::Unusable("string"),
Ok(Value::Object(_)) => Language::Texts(Translations::default()),
Ok(Value::Array(array)) => {
let mut texts = Translations::with_capacity_and_hasher(array.len(), Hasher::default());
for (key, value) in array.iter() {
let key = match key {
KeyRef::Int(i) => i.to_string(),
KeyRef::Str(s) => String::from_utf8_lossy(s).into_owned(),
};
let Value::Str(text) = value else {
return Err(Error::Unsupported(format!("Translation \"{key}\" is not a string.")));
};
texts.insert(key, String::from_utf8_lossy(text).into_owned());
}
Language::Texts(texts)
}
Ok(Value::Ext(never)) => match never {},
};
self.languages.insert(name.into(), language);
Ok(())
}
fn check(&self, name: &str) -> Result<(), Error> {
if self.exceptions && !self.languages.contains_key(name) {
return Err(Error::Exception("Locale not found".into()));
}
Ok(())
}
fn lookup(&self, name: &str) -> Result<&Translations, Error> {
match self.languages.get(name).map(Language::resolve) {
Some(Ok(t)) => Ok(t),
Some(Err(given)) => Err(key_exists_error(given)),
None => Err(key_exists_error("null")),
}
}
}
fn key_exists_error(given: &str) -> Error {
Error::Type(format!("array_key_exists(): Argument #2 ($array) must be of type array, {given} given"))
}
#[derive(Debug, Clone)]
pub struct Locale<'a> {
languages: &'a Languages,
default: Cow<'a, str>,
fallback: Option<Cow<'a, str>>,
}
impl<'a> Locale<'a> {
pub fn new(languages: &'a Languages, default: &'a str) -> Result<Self, Error> {
languages.check(default)?;
Ok(Self { languages, default: Cow::Borrowed(default), fallback: None })
}
pub fn with(
languages: &'a Languages,
default: impl Into<Cow<'a, str>>,
fallback: Option<impl Into<Cow<'a, str>>>,
) -> Self {
Self { languages, default: default.into(), fallback: fallback.map(Into::into) }
}
pub fn default(&self) -> &str {
&self.default
}
pub fn fallback(&self) -> Option<&str> {
self.fallback.as_deref()
}
pub fn set_default(&mut self, name: &str) -> Result<&mut Self, Error> {
self.languages.check(name)?;
self.default = Cow::Owned(name.to_owned());
Ok(self)
}
pub fn set_fallback(&mut self, name: &str) -> Result<&mut Self, Error> {
self.languages.check(name)?;
self.fallback = Some(Cow::Owned(name.to_owned()));
Ok(self)
}
pub fn text<'s>(
&'s self,
key: &str,
missing: Missing<'s>,
placeholders: &[(&str, &str)],
) -> Result<Option<Cow<'s, str>>, Error> {
self.text_with(key, missing, placeholders.iter().copied())
}
pub fn text_with<'s, N: AsRef<str>, V: AsRef<str>>(
&'s self,
key: &str,
missing: Missing<'s>,
placeholders: impl IntoIterator<Item = (N, V)>,
) -> Result<Option<Cow<'s, str>>, Error> {
let default = self.languages.lookup(&self.default)?.get(key);
let fallback = match self.languages.languages.get(self.fallback.as_deref().unwrap_or("")).map(Language::resolve)
{
None | Some(Err("null")) => None,
Some(Err(given)) => return Err(key_exists_error(given)),
Some(Ok(t)) => t.get(key),
};
let usable = |text: Option<&'s String>| text.filter(|text| !text.is_empty());
let text = match (usable(default), usable(fallback)) {
(Some(text), _) | (None, Some(text)) => Some(Cow::Borrowed(text.as_str())),
_ if default.is_none() && fallback.is_none() && self.languages.exceptions => {
return Err(Error::Exception(format!("Key named \"{key}\" not found")));
}
_ => match missing {
Missing::Key | Missing::Text(DEFAULT_DYNAMIC_KEY) => Some(Cow::Owned(format!("{{{{{key}}}}}"))),
Missing::Text(text) => Some(Cow::Borrowed(text)),
Missing::Null => None,
},
};
Ok(text.map(|text| replace_placeholders(text, placeholders)))
}
pub fn translations(&self) -> Result<&'a Translations, Error> {
match self.languages.languages.get(self.default.as_ref()).map(Language::resolve) {
Some(Ok(t)) => Ok(t),
Some(Err(given)) => Err(returned_error(given)),
None => Err(returned_error("null")),
}
}
}
fn replace_placeholders<'s, N: AsRef<str>, V: AsRef<str>>(
mut text: Cow<'s, str>,
placeholders: impl IntoIterator<Item = (N, V)>,
) -> Cow<'s, str> {
let mut spare = String::new();
for (name, value) in placeholders {
let (name, value) = (name.as_ref(), value.as_ref());
let width = name.len() + 4;
let (mut copied, mut from) = (0, 0);
let mut out = std::mem::take(&mut spare);
out.clear();
let bytes = text.as_bytes();
while let Some(found) = bytes[from..].windows(2).position(|pair| pair == b"{{") {
let at = from + found;
let rest = &text[at + 2..];
if rest.starts_with(name) && rest[name.len()..].starts_with("}}") {
if copied == 0 {
out.reserve(text.len() + value.len());
}
out.push_str(&text[copied..at]);
out.push_str(value);
copied = at + width;
from = copied;
} else {
from = at + 1;
}
}
if copied == 0 {
spare = out;
continue;
}
out.push_str(&text[copied..]);
spare = match std::mem::replace(&mut text, Cow::Owned(out)) {
Cow::Owned(previous) => previous,
Cow::Borrowed(_) => String::new(),
};
}
text
}
fn returned_error(given: &str) -> Error {
Error::Type(format!(
"Utopia\\Locale\\Locale::getTranslations(): Return value must be of type array, {given} returned"
))
}
#[cfg(test)]
mod tests {
use super::*;
fn str_replaced(text: &str, placeholders: &[(&str, &str)]) -> String {
let mut text = text.as_bytes().to_vec();
for (name, value) in placeholders {
let search = format!("{{{{{name}}}}}");
text = php_std::string::str_replace(search.as_bytes(), value.as_bytes(), &text).0.into_owned();
}
String::from_utf8(text).unwrap()
}
#[test]
fn placeholders_replace_like_str_replace() {
const PIECES: [&str; 12] = ["{{", "}}", "{", "}", "a", "b", "{{a}}", "{{b}}", "é", "{{{a}}}", "", "{{}}"];
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
let mut next = |n: usize| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % n as u64) as usize
};
for _ in 0..20_000 {
let mut pick = |n: usize| (0..n).map(|_| PIECES[next(PIECES.len())]).collect::<String>();
let text = pick(6);
let (n1, v1, n2, v2) = (pick(1), pick(2), pick(1), pick(2));
let placeholders = [(n1.as_str(), v1.as_str()), (n2.as_str(), v2.as_str())];
assert_eq!(
replace_placeholders(Cow::Borrowed(&text), placeholders),
str_replaced(&text, &placeholders),
"{text:?} {placeholders:?}"
);
}
}
fn languages() -> Languages {
let mut l = Languages::new();
l.insert(
"en-US",
Translations::from_iter([
("hello".to_owned(), "Hello".to_owned()),
("world".to_owned(), "World".to_owned()),
("helloPlaceholder".to_owned(), "Hello {{name}} {{surname}}!".to_owned()),
]),
);
l.insert("he-IL", Translations::from_iter([("hello".to_owned(), "שלום".to_owned())]));
l
}
#[test]
fn texts_and_fallbacks() {
let mut l = languages();
l.set_exceptions(false);
let mut locale = Locale::new(&l, "he-IL").unwrap();
assert_eq!(locale.text("world", Missing::Key, &[]).unwrap().as_deref(), Some("{{world}}"));
locale.set_fallback("en-US").unwrap();
assert_eq!(locale.text("world", Missing::Key, &[]).unwrap().as_deref(), Some("World"));
assert_eq!(locale.text("missing", Missing::Null, &[]).unwrap(), None);
locale.set_default("en-US").unwrap();
let text = locale.text("helloPlaceholder", Missing::Key, &[("name", "{{surname}}"), ("surname", "B")]).unwrap();
assert_eq!(text.as_deref(), Some("Hello B B!"));
}
#[test]
fn errors_like_php() {
let l = languages();
assert_eq!(Locale::new(&l, "xx").unwrap_err(), Error::Exception("Locale not found".into()));
let locale = Locale::new(&l, "he-IL").unwrap();
assert_eq!(locale.text("world", Missing::Key, &[]).unwrap_err().to_string(), "Key named \"world\" not found");
let mut l = Languages::new();
l.insert_json("bad", b"{").unwrap();
l.insert_json("num", b"5").unwrap();
let bad = Locale::new(&l, "bad").unwrap();
assert_eq!(bad.text("a", Missing::Key, &[]).unwrap_err().php_class(), "TypeError");
assert!(bad.translations().unwrap_err().to_string().ends_with("null returned"));
let num = Locale::with(&l, "num", None::<&str>);
assert!(num.text("a", Missing::Key, &[]).unwrap_err().to_string().ends_with("int given"));
}
#[test]
fn object_of_strings_check_matches_the_decoder() {
let inputs: &[&[u8]] = &[
br#"{"a":"b"}"#,
br#"{}"#,
br#" {"a" : "b" } "#,
br#"{"a":"b","a":"c"}"#,
br#"{"a":1}"#,
br#"{"a":null}"#,
br#"{"a":["b"]}"#,
br#"{"a":{"b":"c"}}"#,
br#"{"\u00e9":"\u00e9\n"}"#,
br#"{"a":"\ud800"}"#,
br#"{"a":"b"} x"#,
br#"{"a":"b""#,
br#"[]"#,
br#"["a"]"#,
br#""a""#,
b"null",
b"1",
b"",
b"\xff",
];
for input in inputs {
assert_eq!(
is_object_of_strings(input),
serde_json::from_slice::<Translations>(input).is_ok(),
"{}",
String::from_utf8_lossy(input)
);
}
}
#[test]
fn json_files_are_shared_and_decoded_on_first_use() {
let json = br#"{"hello":"Hello","bye":"Bye"}"#;
let mut lazy = Languages::new();
lazy.insert_json("en", json).unwrap();
lazy.insert_json("en-us", json).unwrap();
lazy.insert_json("fr", br#"{"hello":"Bonjour"}"#).unwrap();
assert_eq!(lazy.files.len(), 2);
let (Some(Language::Json(en)), Some(Language::Json(en_us))) =
(lazy.languages.get("en"), lazy.languages.get("en-us"))
else {
panic!("a JSON object of strings is kept as its text");
};
assert!(Arc::ptr_eq(en, en_us));
assert!(en.texts.get().is_none(), "nothing is decoded before a lookup");
let locale = Locale::new(&lazy, "en-us").unwrap();
assert_eq!(locale.text("hello", Missing::Null, &[]).unwrap().as_deref(), Some("Hello"));
assert!(en.texts.get().is_some() && Arc::ptr_eq(en, en_us), "decoded once, for both names");
let mut eager = Languages::new();
for (name, texts) in [("en", json.as_slice()), ("en-us", json), ("fr", br#"{"hello":"Bonjour"}"#)] {
eager.insert(name, serde_json::from_slice(texts).unwrap());
}
assert_eq!(lazy, eager);
}
}