laraindexnow 0.1.2

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
use laravel::db::Value;
use laravel::time::Timestamp;

/// A column value, in the small set of shapes the tracking conditions compare.
///
/// Laravel Rust models are typed structs, so a condition named by an attribute cannot read a field
/// by name. The registration reads every column through the model's metadata and turns it into an
/// `Attr`, which is what `when("status", "published")` and friends compare against.
#[derive(Debug, Clone, PartialEq)]
pub enum Attr {
    /// A SQL `NULL`, or a column the model does not have.
    Null,
    /// A boolean.
    Bool(bool),
    /// Any integer column.
    Int(i64),
    /// A floating point column.
    Float(f64),
    /// Text, enums stored as text, and anything else that reads as a string (UUIDs, decimals).
    Text(String),
    /// A point in time.
    Time(Timestamp),
}

impl Attr {
    /// Whether the value is `Null`.
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// The text, when this is text.
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(text) => Some(text),
            _ => None,
        }
    }

    /// The integer, when this is an integer.
    pub fn as_int(&self) -> Option<i64> {
        match self {
            Self::Int(value) => Some(*value),
            _ => None,
        }
    }

    /// The boolean, when this is a boolean.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    /// The point in time, when this is one.
    pub fn as_time(&self) -> Option<Timestamp> {
        match self {
            Self::Time(value) => Some(*value),
            _ => None,
        }
    }

    /// The value as it reads in a URL template: text as it is, numbers and booleans spelled out.
    pub fn to_url_part(&self) -> Option<String> {
        match self {
            Self::Null => None,
            Self::Bool(value) => Some(value.to_string()),
            Self::Int(value) => Some(value.to_string()),
            Self::Float(value) => Some(value.to_string()),
            Self::Text(value) => Some(value.clone()),
            Self::Time(value) => Some(value.to_string()),
        }
    }

    /// Truth the way PHP reads it, so `1`, `"1"` and `true` pass while `0`, `"0"`, `""` and `null`
    /// do not. That covers a flag stored as an integer, and a counter: "has at least one".
    pub fn truthy(&self) -> bool {
        match self {
            Self::Null => false,
            Self::Bool(value) => *value,
            Self::Int(value) => *value != 0,
            Self::Float(value) => *value != 0.0,
            Self::Text(value) => !value.is_empty() && value != "0",
            Self::Time(_) => true,
        }
    }

    fn as_flag(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            Self::Int(1) => Some(true),
            Self::Int(0) => Some(false),
            Self::Text(value) if value == "1" => Some(true),
            Self::Text(value) if value == "0" => Some(false),
            _ => None,
        }
    }

    fn as_number(&self) -> Option<f64> {
        match self {
            Self::Int(value) => Some(*value as f64),
            Self::Float(value) => Some(*value),
            _ => None,
        }
    }

    /// Whether two values are the same one.
    ///
    /// A boolean on either side compares as a flag (`true` matches `1` and `"1"`), and anything
    /// else only matches itself, so a condition on `true` never quietly matches a stray string.
    /// Integers and floats compare by number.
    pub fn matches(&self, expected: &Attr) -> bool {
        if matches!(self, Self::Bool(_)) || matches!(expected, Self::Bool(_)) {
            return match (self.as_flag(), expected.as_flag()) {
                (Some(left), Some(right)) => left == right,
                _ => false,
            };
        }

        match (self.as_number(), expected.as_number()) {
            (Some(left), Some(right)) => left == right,
            _ => self == expected,
        }
    }

    /// Orders two values, when they can be ordered. Something against nothing has no answer.
    pub fn compare(&self, other: &Attr) -> Option<std::cmp::Ordering> {
        if let (Some(left), Some(right)) = (self.as_number(), other.as_number()) {
            return left.partial_cmp(&right);
        }

        match (self, other) {
            (Self::Text(left), Self::Text(right)) => Some(left.cmp(right)),
            (Self::Time(left), Self::Time(right)) => Some(left.cmp(right)),
            _ => None,
        }
    }
}

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

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

from_int!(i8, i16, i32, i64, u8, u16, u32);

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

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

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

impl From<Timestamp> for Attr {
    fn from(value: Timestamp) -> Self {
        Self::Time(value)
    }
}

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

impl From<&Value<'_>> for Attr {
    fn from(value: &Value<'_>) -> Self {
        match value {
            Value::Boolean(value) => value.map_or(Self::Null, Self::Bool),
            Value::SmallInteger(value) => value.map_or(Self::Null, |value| Self::Int(i64::from(value))),
            Value::Integer(value) => value.map_or(Self::Null, |value| Self::Int(i64::from(value))),
            Value::BigInteger(value) => value.map_or(Self::Null, Self::Int),
            Value::UnsignedInteger(value) => value.map_or(Self::Null, |value| {
                i64::try_from(value).map_or(Self::Float(value as f64), Self::Int)
            }),
            Value::Real(value) => value.map_or(Self::Null, |value| Self::Float(f64::from(value))),
            Value::Double(value) => value.map_or(Self::Null, Self::Float),
            Value::Text(value) => value.as_ref().map_or(Self::Null, |value| Self::Text(value.to_string())),
            Value::Timestamp(value) => value.map_or(Self::Null, Self::Time),
            Value::DateTime(value) => value.map_or(Self::Null, |value| {
                value
                    .in_tz("UTC")
                    .map_or(Self::Null, |zoned| Self::Time(zoned.timestamp()))
            }),
            Value::Date(value) => value.map_or(Self::Null, |value| Self::Text(value.to_string())),
            Value::Uuid(value) => value.map_or(Self::Null, |value| Self::Text(value.to_string())),
            Value::Ulid(value) => value.map_or(Self::Null, |value| Self::Text(value.to_string())),
            Value::Decimal(value) => value.as_ref().map_or(Self::Null, |value| Self::Text(value.to_string())),
            _ => Self::Null,
        }
    }
}