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::fmt;
use std::sync::Arc;

use indexmap::IndexMap;
use laravel::str::Str;

use crate::support::{is_numeric, ucfirst};

/// A value a placeholder is replaced with.
///
/// PHP takes any value in the `$replace` array, so this takes the same: text, numbers, booleans,
/// nothing at all, and a closure that wraps the content of a `<name>...</name>` tag.
#[derive(Clone)]
pub enum ReplaceValue {
    /// Text.
    Text(String),
    /// An integer.
    Int(i64),
    /// A decimal number.
    Float(f64),
    /// A boolean, which is `1` or an empty string as in PHP.
    Bool(bool),
    /// Nothing, which is an empty string.
    Null,
    /// A function from the content of `<name>...</name>` to what replaces the whole tag.
    Callback(Arc<dyn Fn(&str) -> String + Send + Sync>),
}

impl ReplaceValue {
    /// A closure that wraps the content of a `<name>...</name>` tag, such as a link.
    ///
    /// ```
    /// use laratext::{Replace, ReplaceValue};
    ///
    /// let replace = Replace::new().with(
    ///     "link",
    ///     ReplaceValue::callback(|inner| format!("<a href=\"/terms\">{inner}</a>")),
    /// );
    /// ```
    pub fn callback(callback: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
        Self::Callback(Arc::new(callback))
    }

    /// The value as PHP would write it in a string.
    pub fn to_text(&self) -> String {
        match self {
            Self::Text(text) => text.clone(),
            Self::Int(number) => number.to_string(),
            Self::Float(number) => number.to_string(),
            Self::Bool(true) => "1".to_owned(),
            Self::Bool(false) | Self::Null | Self::Callback(_) => String::new(),
        }
    }

    /// PHP's `is_numeric`: numbers and numeric strings.
    pub fn is_numeric(&self) -> bool {
        match self {
            Self::Int(_) => true,
            Self::Float(number) => number.is_finite(),
            Self::Text(text) => is_numeric(text),
            _ => false,
        }
    }

    /// The value as a number, when it is numeric.
    pub fn as_number(&self) -> Option<f64> {
        match self {
            Self::Int(number) => Some(*number as f64),
            Self::Float(number) if number.is_finite() => Some(*number),
            Self::Text(text) if is_numeric(text) => text.trim().parse().ok(),
            _ => None,
        }
    }
}

impl fmt::Debug for ReplaceValue {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text(text) => formatter.debug_tuple("Text").field(text).finish(),
            Self::Int(number) => formatter.debug_tuple("Int").field(number).finish(),
            Self::Float(number) => formatter.debug_tuple("Float").field(number).finish(),
            Self::Bool(value) => formatter.debug_tuple("Bool").field(value).finish(),
            Self::Null => formatter.write_str("Null"),
            Self::Callback(_) => formatter.write_str("Callback"),
        }
    }
}

macro_rules! from_integer {
    ($($type:ty),*) => {
        $(impl From<$type> for ReplaceValue {
            fn from(value: $type) -> Self {
                Self::Int(value as i64)
            }
        })*
    };
}

from_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);

impl From<f32> for ReplaceValue {
    fn from(value: f32) -> Self {
        Self::Float(f64::from(value))
    }
}

impl From<f64> for ReplaceValue {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<bool> for ReplaceValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<&str> for ReplaceValue {
    fn from(value: &str) -> Self {
        Self::Text(value.to_owned())
    }
}

impl From<String> for ReplaceValue {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&String> for ReplaceValue {
    fn from(value: &String) -> Self {
        Self::Text(value.clone())
    }
}

impl<T: Into<ReplaceValue>> From<Option<T>> for ReplaceValue {
    fn from(value: Option<T>) -> Self {
        value.map_or(Self::Null, Into::into)
    }
}

/// The values of the placeholders of a text, PHP's `$replace` array: `:name` takes the value of
/// `name`, `:Name` and `:NAME` take it with its first letter or all of it in capitals, and a
/// closure wraps a `<name>...</name>` tag.
///
/// Build it with [`replace!`](crate::replace!) or with [`Replace::with`]:
///
/// ```
/// use laratext::{Replace, replace};
///
/// let by_macro = replace! { name => "John", count => 5 };
/// let by_hand = Replace::new().with("name", "John").with("count", 5);
///
/// assert_eq!(by_macro.len(), by_hand.len());
/// ```
#[derive(Debug, Clone, Default)]
pub struct Replace(IndexMap<String, ReplaceValue>);

impl Replace {
    /// No replacements.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a value, replacing an earlier one of the same name.
    #[must_use]
    pub fn with(mut self, name: impl Into<String>, value: impl Into<ReplaceValue>) -> Self {
        self.insert(name, value);

        self
    }

    /// Add a value, replacing an earlier one of the same name.
    pub fn insert(&mut self, name: impl Into<String>, value: impl Into<ReplaceValue>) -> &mut Self {
        self.0.insert(name.into(), value.into());

        self
    }

    /// The value of a placeholder.
    pub fn get(&self, name: &str) -> Option<&ReplaceValue> {
        self.0.get(name)
    }

    /// Whether there are no values.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// How many values there are.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// The values in the order they were added.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &ReplaceValue)> {
        self.0.iter()
    }

    /// The quantity, `count` in PHP, when there is a numeric one.
    pub fn count(&self) -> Option<f64> {
        self.get("count").and_then(ReplaceValue::as_number)
    }
}

impl<K: Into<String>, V: Into<ReplaceValue>> FromIterator<(K, V)> for Replace {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut replace = Self::new();

        for (name, value) in iter {
            replace.insert(name, value);
        }

        replace
    }
}

/// Build the [`Replace`] of a text.
///
/// ```
/// use laratext::replace;
///
/// let replace = replace! { name => "John", "item_count" => 5 };
///
/// assert_eq!(replace.len(), 2);
/// ```
///
/// A name is an identifier or a string.
#[macro_export]
macro_rules! replace {
    () => {
        $crate::Replace::new()
    };
    ($($name:tt => $value:expr),+ $(,)?) => {{
        let mut replace = $crate::Replace::new();

        $(replace.insert($crate::replace::name(stringify!($name)), $value);)+

        replace
    }};
}

/// The name a [`replace!`](crate::replace!) entry was written with.
#[doc(hidden)]
pub fn name(written: &str) -> &str {
    written
        .strip_prefix('"')
        .and_then(|rest| rest.strip_suffix('"'))
        .unwrap_or(written)
}

/// Laravel's `makeReplacements`: `:name`, `:Name` and `:NAME`, the longest placeholder first and
/// in a single pass, and a closure wrapping `<name>...</name>`.
pub fn make_replacements(line: &str, replace: &Replace) -> String {
    if replace.is_empty() {
        return line.to_owned();
    }

    let mut line = line.to_owned();
    let mut pairs: IndexMap<String, String> = IndexMap::new();

    for (name, value) in replace.iter() {
        if let ReplaceValue::Callback(callback) = value {
            line = wrap(&line, name, callback.as_ref());

            continue;
        }

        let value = value.to_text();

        pairs.insert(format!(":{}", ucfirst(name)), ucfirst(&value));
        pairs.insert(format!(":{}", name.to_uppercase()), value.to_uppercase());
        pairs.insert(format!(":{name}"), value);
    }

    if pairs.is_empty() {
        return line;
    }

    let pairs: Vec<(&str, &str)> = pairs.iter().map(|(from, to)| (from.as_str(), to.as_str())).collect();

    line.swap(&pairs)
}

/// What `preg_replace_callback('/<name>(.*?)<\/name>/', ...)` does: the closest `</name>` after
/// each `<name>` on the same line.
fn wrap(line: &str, name: &str, callback: &(dyn Fn(&str) -> String + Send + Sync)) -> String {
    let open = format!("<{name}>");
    let close = format!("</{name}>");
    let mut result = String::with_capacity(line.len());
    let mut rest = line;

    while let Some(start) = rest.find(&open) {
        let inner_start = start + open.len();
        let after = &rest[inner_start..];

        let closed = after.find(&close).filter(|end| !after[..*end].contains('\n'));

        match closed {
            Some(end) => {
                result.push_str(&rest[..start]);
                result.push_str(&callback(&after[..end]));

                rest = &after[end + close.len()..];
            }
            None => {
                // Not a tag: keep the first character and look further on.
                let step = start + rest[start..].chars().next().map_or(1, char::len_utf8);

                result.push_str(&rest[..step]);

                rest = &rest[step..];
            }
        }
    }

    result.push_str(rest);

    result
}