use std::path::PathBuf;
use laravel::context::Context;
use crate::config::TextsConfig;
pub fn settings<R>(read: impl FnOnce(&TextsConfig) -> R) -> R {
if Context::current().is_none() {
return read(&TextsConfig::default());
}
let config = laravel::config();
match config.get::<TextsConfig>() {
Some(section) => read(section),
None => read(&TextsConfig::default()),
}
}
pub fn config() -> TextsConfig {
settings(Clone::clone)
}
pub fn base_path() -> PathBuf {
if Context::current().is_none() {
return PathBuf::from(".");
}
laravel::config().app.base_path.clone()
}
pub fn lang_path() -> PathBuf {
let folder = settings(|config| config.lang_path.clone());
base_path().join(folder)
}
pub fn lang_file(locale: &str) -> PathBuf {
lang_path().join(format!("{locale}.json"))
}
pub fn source_locale() -> String {
settings(|config| config.source_locale.clone())
.filter(|locale| !locale.is_empty())
.unwrap_or_else(laralocale::locale)
}
pub fn ucfirst(value: &str) -> String {
let mut chars = value.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
pub fn ucwords(value: &str) -> String {
let mut result = String::with_capacity(value.len());
let mut start = true;
for character in value.chars() {
if start {
result.extend(character.to_uppercase());
} else {
result.push(character);
}
start = matches!(character, ' ' | '\t' | '\r' | '\n' | '\x0b' | '\x0c');
}
result
}
pub fn key_to_text(key: &str) -> String {
let last = key.rsplit('.').next().unwrap_or(key);
ucwords(&last.replace('_', " "))
}
pub fn is_numeric(value: &str) -> bool {
let value = value.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c'));
let bytes = value.as_bytes();
let mut index = 0;
if matches!(bytes.first(), Some(b'+' | b'-')) {
index += 1;
}
let digits = |from: usize| bytes[from..].iter().take_while(|byte| byte.is_ascii_digit()).count();
let whole = digits(index);
index += whole;
let mut fraction = 0;
if bytes.get(index) == Some(&b'.') {
fraction = digits(index + 1);
index += 1 + fraction;
}
if whole == 0 && fraction == 0 {
return false;
}
if matches!(bytes.get(index), Some(b'e' | b'E')) {
let mut exponent = index + 1;
if matches!(bytes.get(exponent), Some(b'+' | b'-')) {
exponent += 1;
}
let exponent_digits = digits(exponent);
if exponent_digits == 0 {
return false;
}
index = exponent + exponent_digits;
}
index == bytes.len()
}