laraindexnow 0.1.0

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
use std::collections::BTreeMap;

use laravel::model::{Changes, Model};

use crate::value::Attr;

static NULL: Attr = Attr::Null;

/// The state of a model at one moment, by column name.
///
/// Conditions are evaluated against records rather than against the typed model, because a
/// condition such as `was("status", "draft")` has to read the state the record held *before* the
/// write, and Laravel Rust does not hand a model's previous state over as a model.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Record {
    values: BTreeMap<String, Attr>,
}

impl Record {
    /// An empty record, for tests and custom sources.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set one attribute.
    #[must_use]
    pub fn with(mut self, attribute: &str, value: impl Into<Attr>) -> Self {
        self.values.insert(attribute.to_owned(), value.into());

        self
    }

    /// Read every column of a model.
    pub fn of<M: Model>(model: &M) -> Self {
        let values = M::META
            .columns
            .iter()
            .map(|field| (field.name.to_owned(), Attr::from(&(field.value)(model))))
            .collect();

        Self { values }
    }

    /// The state a model held before an update: its current columns, with each changed column put
    /// back to the value it had.
    pub fn before<M: Model>(model: &M, changes: &Changes<M>) -> Self {
        let mut record = Self::of(model);

        for change in changes {
            record.values.insert(change.column.to_owned(), Attr::from(&change.old));
        }

        record
    }

    /// A column's value, or `Attr::Null` when the model has no such column.
    pub fn get(&self, attribute: &str) -> &Attr {
        self.values.get(attribute).unwrap_or(&NULL)
    }

    /// A text column.
    pub fn text(&self, attribute: &str) -> Option<&str> {
        self.get(attribute).as_text()
    }

    /// An integer column.
    pub fn int(&self, attribute: &str) -> Option<i64> {
        self.get(attribute).as_int()
    }

    /// A boolean column.
    pub fn bool(&self, attribute: &str) -> Option<bool> {
        self.get(attribute).as_bool()
    }

    /// The column names the record holds.
    pub fn attributes(&self) -> impl Iterator<Item = &str> {
        self.values.keys().map(String::as_str)
    }
}

/// What kind of write a [`Change`] describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeKind {
    /// A row was inserted.
    Created,
    /// A row was updated.
    Updated,
    /// A row was deleted.
    Deleted,
}

/// One write, as the transition conditions see it: the state before and the state after.
///
/// A created record has no state before, so reading an attribute `was` gives `Attr::Null`.
#[derive(Debug, Clone, Copy)]
pub struct Change<'a> {
    /// The kind of write.
    pub kind: ChangeKind,
    /// The record after the write.
    pub after: &'a Record,
    /// The record before the write, when there was one.
    pub before: Option<&'a Record>,
}

impl Change<'_> {
    /// The attribute now.
    pub fn is(&self, attribute: &str) -> &Attr {
        self.after.get(attribute)
    }

    /// The attribute before this write.
    pub fn was(&self, attribute: &str) -> &Attr {
        self.before.map_or(&NULL, |before| before.get(attribute))
    }

    /// Whether any of these attributes changed, or any attribute at all when none is named.
    pub fn changed(&self, attributes: &[String]) -> bool {
        let Some(before) = self.before else {
            return true;
        };

        if attributes.is_empty() {
            return before != self.after;
        }

        attributes
            .iter()
            .any(|attribute| !before.get(attribute).matches(self.after.get(attribute)))
    }

    /// The attribute holds `to` now and did not before.
    pub fn became(&self, attribute: &str, to: &Attr) -> bool {
        self.is(attribute).matches(to) && !self.was(attribute).matches(to)
    }

    /// The attribute held `from` and no longer does.
    pub fn left(&self, attribute: &str, from: &Attr) -> bool {
        self.was(attribute).matches(from) && !self.is(attribute).matches(from)
    }

    /// The attribute holds `value` now.
    pub fn holds(&self, attribute: &str, value: &Attr) -> bool {
        self.is(attribute).matches(value)
    }

    /// The attribute held `value` before this write.
    pub fn held(&self, attribute: &str, value: &Attr) -> bool {
        self.was(attribute).matches(value)
    }

    /// Whether this write created the record.
    pub fn created(&self) -> bool {
        self.kind == ChangeKind::Created
    }

    /// Whether this write updated the record.
    pub fn updated(&self) -> bool {
        self.kind == ChangeKind::Updated
    }

    /// Whether this write deleted the record.
    pub fn deleted(&self) -> bool {
        self.kind == ChangeKind::Deleted
    }
}