laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
use std::path::PathBuf;

use laravel::context::Context;

use crate::config::TextsConfig;

/// Reads the package's configuration, or its defaults when there is no application, such as in a
/// plain `tokio` test.
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()),
    }
}

/// A copy of the package's configuration.
pub fn config() -> TextsConfig {
    settings(Clone::clone)
}

/// The application's base path, or the working directory when there is no application.
pub fn base_path() -> PathBuf {
    if Context::current().is_none() {
        return PathBuf::from(".");
    }

    laravel::config().app.base_path.clone()
}

/// The folder with the `{locale}.json` files, the equivalent of `lang_path()`.
pub fn lang_path() -> PathBuf {
    let folder = settings(|config| config.lang_path.clone());

    base_path().join(folder)
}

/// The language file of a locale.
pub fn lang_file(locale: &str) -> PathBuf {
    lang_path().join(format!("{locale}.json"))
}

/// The locale the texts in the code are written in: `source_locale`, or the application's default
/// locale.
pub fn source_locale() -> String {
    settings(|config| config.source_locale.clone())
        .filter(|locale| !locale.is_empty())
        .unwrap_or_else(laralocale::locale)
}

/// PHP's `ucfirst` for a string with multibyte characters.
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(),
    }
}

/// PHP's `ucwords`: the first letter of each word, where words are separated by whitespace.
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
}

/// The text a key stands for when no source text is given: the last part after a dot, with the
/// underscores read as spaces and each word capitalised.
pub fn key_to_text(key: &str) -> String {
    let last = key.rsplit('.').next().unwrap_or(key);

    ucwords(&last.replace('_', " "))
}

/// PHP's `is_numeric` for a string.
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()
}