oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
Documentation
use super::render_error;
use crate::error::Result;
use crate::library::CallLimits;
use crate::value::{Arg, Value};
use laravel_rust_format_core::PhpNumber;
use serde_json::Value as Json;

#[derive(Clone, Copy)]
pub(super) struct Args<'s, 'a, 'c> {
    name: &'s str,
    values: &'s [Arg<'a, 'c>],
    offset: usize,
    pub(super) limits: CallLimits,
}

impl<'s, 'a, 'c> Args<'s, 'a, 'c> {
    pub(super) fn new(name: &'s str, values: &'s [Arg<'a, 'c>]) -> Self {
        Self {
            name,
            values,
            offset: 0,
            limits: CallLimits::default(),
        }
    }

    pub(super) fn with_limits(self, limits: CallLimits) -> Self {
        Self { limits, ..self }
    }

    pub(super) fn skip(self, count: usize) -> Self {
        Self {
            values: &self.values[count.min(self.values.len())..],
            offset: self.offset + count,
            ..self
        }
    }

    pub(super) fn len(self) -> usize {
        self.values.len()
    }

    pub(super) fn check(self, min: usize, max: usize) -> Result<()> {
        if (min..=max).contains(&self.len()) {
            return Ok(());
        }
        let min = min + self.offset;
        let max = max.saturating_add(self.offset);
        let expected = match max {
            max if min == max => min.to_string(),
            usize::MAX => format!("at least {min}"),
            _ => format!("{min} to {max}"),
        };
        Err(render_error(format!(
            "{} expects {expected} arguments, got {}",
            self.name,
            self.len() + self.offset
        )))
    }

    pub(super) fn value(self, index: usize) -> Result<&'s Value<'a>> {
        match self.values.get(index) {
            Some(Arg::Value(value)) => Ok(value),
            _ => Err(self.invalid(index, "a value")),
        }
    }

    pub(super) fn invalid(self, index: usize, expected: &str) -> crate::error::Error {
        render_error(format!(
            "{} argument {} must be {expected}",
            self.name,
            self.offset + index + 1
        ))
    }

    pub(super) fn str(self, index: usize) -> Result<&'s str> {
        string(self.value(index)?).ok_or_else(|| self.invalid(index, "a string"))
    }

    pub(super) fn str_or(self, index: usize, default: &'s str) -> Result<&'s str> {
        if index < self.len() {
            self.str(index)
        } else {
            Ok(default)
        }
    }

    pub(super) fn number(self, index: usize) -> Result<PhpNumber> {
        match self.value(index)? {
            Value::Int(value) => Ok(PhpNumber::Int(*value)),
            Value::Float(value) => Ok(PhpNumber::Float(*value)),
            Value::Json(Json::Number(value)) => {
                if let Some(value) = value.as_i64() {
                    return Ok(PhpNumber::Int(value));
                }
                value
                    .as_f64()
                    .map(PhpNumber::Float)
                    .ok_or_else(|| self.invalid(index, "a number"))
            }
            _ => Err(self.invalid(index, "a number")),
        }
    }

    pub(super) fn number_or(self, index: usize, default: i64) -> Result<PhpNumber> {
        if index < self.len() {
            self.number(index)
        } else {
            Ok(default.into())
        }
    }

    pub(super) fn int(self, index: usize) -> Result<i64> {
        match self.value(index)? {
            Value::Int(value) => Ok(*value),
            Value::Json(Json::Number(value)) => value
                .as_i64()
                .ok_or_else(|| self.invalid(index, "an integer")),
            _ => Err(self.invalid(index, "an integer")),
        }
    }

    pub(super) fn int_or(self, index: usize, default: i64) -> Result<i64> {
        Ok(self.opt_int(index)?.unwrap_or(default))
    }

    pub(super) fn opt_int(self, index: usize) -> Result<Option<i64>> {
        if self.is_null(index) {
            Ok(None)
        } else {
            self.int(index).map(Some)
        }
    }

    pub(super) fn opt_str(self, index: usize) -> Result<Option<&'s str>> {
        if self.is_null(index) {
            Ok(None)
        } else {
            self.str(index).map(Some)
        }
    }

    pub(super) fn is_null(self, index: usize) -> bool {
        matches!(
            self.values.get(index),
            None | Some(Arg::Value(Value::Null | Value::Json(Json::Null)))
        )
    }

    pub(super) fn bool_or(self, index: usize, default: bool) -> Result<bool> {
        match self.values.get(index) {
            None => Ok(default),
            Some(Arg::Value(Value::Bool(value) | Value::Json(Json::Bool(value)))) => Ok(*value),
            _ => Err(self.invalid(index, "a boolean")),
        }
    }

    pub(super) fn strings(self, index: usize) -> Result<Vec<&'s str>> {
        self.optional_strings(index)?
            .into_iter()
            .map(|value| value.ok_or_else(|| self.invalid(index, "a list of strings")))
            .collect()
    }

    pub(super) fn optional_map(self, index: usize) -> Result<Options<'s, 'a, 'c>> {
        let map = if self.is_null(index) {
            None
        } else {
            let map = self.value(index)?;
            if !matches!(map, Value::Map(_) | Value::Json(Json::Object(_))) {
                return Err(self.invalid(index, "an options map"));
            }
            Some(map)
        };
        Ok(Options {
            args: self,
            index,
            map,
        })
    }

    pub(super) fn string_or_list(self, index: usize) -> Result<Vec<&'s str>> {
        match string(self.value(index)?) {
            Some(value) => Ok(vec![value]),
            None => self.strings(index),
        }
    }

    pub(super) fn optional_strings(self, index: usize) -> Result<Vec<Option<&'s str>>> {
        let invalid = || self.invalid(index, "a list of strings or nulls");
        match self.value(index)? {
            Value::List(values) => values
                .iter()
                .map(|value| match value {
                    Value::Null | Value::Json(Json::Null) => Ok(None),
                    _ => string(value).map(Some).ok_or_else(invalid),
                })
                .collect(),
            Value::Json(Json::Array(values)) => values
                .iter()
                .map(|value| match value {
                    Json::Null => Ok(None),
                    Json::String(text) => Ok(Some(text.as_str())),
                    _ => Err(invalid()),
                })
                .collect(),
            _ => Err(invalid()),
        }
    }

    pub(super) fn string_map(self, index: usize) -> Result<Vec<(&'s str, &'s str)>> {
        let invalid = || self.invalid(index, "a map of strings");
        match self.value(index)? {
            Value::Map(values) => values
                .iter()
                .map(|(key, value)| {
                    string(value)
                        .map(|value| (key.as_str(), value))
                        .ok_or_else(invalid)
                })
                .collect(),
            Value::Json(Json::Object(values)) => values
                .iter()
                .map(|(key, value)| {
                    value
                        .as_str()
                        .map(|value| (key.as_str(), value))
                        .ok_or_else(invalid)
                })
                .collect(),
            _ => Err(invalid()),
        }
    }
}

pub(super) struct Options<'s, 'a, 'c> {
    args: Args<'s, 'a, 'c>,
    index: usize,
    map: Option<&'s Value<'a>>,
}

impl<'s, 'a> Options<'s, 'a, '_> {
    pub(super) fn get(&self, key: &str) -> Option<Value<'a>> {
        self.map?.field(key).filter(|value| !value.is_null())
    }

    pub(super) fn invalid(&self, key: &str, expected: &str) -> crate::error::Error {
        self.args.invalid(
            self.index,
            &format!("an options map with {key:?} set to {expected}"),
        )
    }

    pub(super) fn str_or(&self, key: &str, default: &'s str) -> Result<&'s str> {
        let value = match self.map {
            Some(Value::Map(fields)) => {
                fields.get(key).filter(|value| !value.is_null()).map(string)
            }
            Some(Value::Json(Json::Object(fields))) => fields
                .get(key)
                .filter(|value| !value.is_null())
                .map(Json::as_str),
            _ => None,
        };
        match value {
            Some(Some(value)) => Ok(value),
            Some(None) => Err(self.invalid(key, "a string")),
            None => Ok(default),
        }
    }

    pub(super) fn bool_or(&self, key: &str, default: bool) -> Result<bool> {
        match self.get(key).map(|value| value.scalar()) {
            Some(Value::Bool(value)) => Ok(value),
            Some(_) => Err(self.invalid(key, "a boolean")),
            None => Ok(default),
        }
    }

    pub(super) fn number_or(&self, key: &str, default: i64) -> Result<PhpNumber> {
        match self.get(key).map(|value| value.scalar()) {
            Some(Value::Int(value)) => Ok(PhpNumber::Int(value)),
            Some(Value::Float(value)) => Ok(PhpNumber::Float(value)),
            Some(_) => Err(self.invalid(key, "a number")),
            None => Ok(PhpNumber::Int(default)),
        }
    }
}

pub(super) fn string<'s>(value: &'s Value<'_>) -> Option<&'s str> {
    match value {
        Value::Str(value) | Value::Html(value) => Some(value),
        Value::Json(Json::String(value)) => Some(value),
        _ => None,
    }
}

pub(super) fn formatted<'a>(value: String) -> Result<Value<'a>> {
    Ok(Value::string(value))
}

pub(super) fn from_number<'a>(value: PhpNumber) -> Value<'a> {
    match value {
        PhpNumber::Int(value) => Value::Int(value),
        PhpNumber::Float(value) => Value::Float(value),
    }
}

pub(super) fn text_bytes<'a>(bytes: impl AsRef<[u8]>) -> Result<Value<'a>> {
    let text =
        std::str::from_utf8(bytes.as_ref()).map_err(|error| render_error(error.to_string()))?;
    formatted(text.to_owned())
}

pub(super) fn text_list<'a>(values: impl IntoIterator<Item = impl Into<String>>) -> Value<'a> {
    Value::List(
        values
            .into_iter()
            .map(|value| Value::string(value.into()))
            .collect(),
    )
}