use std::marker::PhantomData;
use std::sync::Arc;
use laravel::db::Values;
use laravel::model::Model;
use crate::policy::Policy;
use crate::record::{Change, Record};
use crate::value::Attr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Op {
Eq,
Ne,
Gt,
Gte,
Lt,
Lte,
}
type RecordPredicate = Arc<dyn Fn(&Record) -> bool + Send + Sync>;
type RecordUrl = Arc<dyn Fn(&Record) -> Option<String> + Send + Sync>;
type ModelUrl<M> = Arc<dyn Fn(&M) -> Option<String> + Send + Sync>;
type ModelUrls<M> = Arc<dyn Fn(&M) -> Vec<String> + Send + Sync>;
#[derive(Clone)]
enum Condition {
Predicate(RecordPredicate),
Holds {
attribute: String,
values: Vec<Attr>,
},
Truthy(String),
Falsy(String),
Compare {
attribute: String,
op: Op,
value: Attr,
},
Was {
attribute: String,
values: Vec<Attr>,
},
Changed(Vec<String>),
Became {
attribute: String,
values: Vec<Attr>,
},
BecameFrom {
attribute: String,
to: Vec<Attr>,
from: Vec<Attr>,
},
Left {
attribute: String,
values: Vec<Attr>,
},
Increments(String),
}
impl Condition {
fn name(&self) -> &'static str {
match self {
Self::Predicate(_) => "predicate",
Self::Holds { .. } => "holds",
Self::Truthy(_) => "truthy",
Self::Falsy(_) => "falsy",
Self::Compare { .. } => "compare",
Self::Was { .. } => "was",
Self::Changed(_) => "changed",
Self::Became { .. } => "became",
Self::BecameFrom { .. } => "becameFrom",
Self::Left { .. } => "left",
Self::Increments(_) => "increments",
}
}
fn is_state(&self) -> bool {
matches!(
self,
Self::Predicate(_) | Self::Holds { .. } | Self::Truthy(_) | Self::Falsy(_) | Self::Compare { .. }
)
}
fn holds_for(&self, record: &Record) -> bool {
match self {
Self::Predicate(predicate) => predicate(record),
Self::Holds { attribute, values } => any_matches(record.get(attribute), values),
Self::Truthy(attribute) => record.get(attribute).truthy(),
Self::Falsy(attribute) => !record.get(attribute).truthy(),
Self::Compare { attribute, op, value } => compares(record.get(attribute), *op, value),
_ => true,
}
}
fn holds_for_change(&self, change: &Change<'_>) -> bool {
match self {
Self::Was { attribute, values } => any_matches(change.was(attribute), values),
Self::Changed(attributes) => change.changed(attributes),
Self::Became { attribute, values } => values.iter().any(|to| change.became(attribute, to)),
Self::BecameFrom { attribute, to, from } => {
to.iter().any(|to| change.holds(attribute, to)) && from.iter().any(|from| change.held(attribute, from))
}
Self::Left { attribute, values } => values.iter().any(|from| change.left(attribute, from)),
Self::Increments(attribute) => increased(change.was(attribute), change.is(attribute)),
state => state.holds_for(change.after),
}
}
}
fn any_matches(actual: &Attr, expected: &[Attr]) -> bool {
expected.iter().any(|candidate| actual.matches(candidate))
}
fn compares(actual: &Attr, op: Op, expected: &Attr) -> bool {
match op {
Op::Eq => actual.matches(expected),
Op::Ne => !actual.matches(expected),
_ => actual.compare(expected).is_some_and(|ordering| match op {
Op::Gt => ordering.is_gt(),
Op::Gte => ordering.is_ge(),
Op::Lt => ordering.is_lt(),
_ => ordering.is_le(),
}),
}
}
fn increased(before: &Attr, after: &Attr) -> bool {
let number = |value: &Attr| match value {
Attr::Int(value) => Some(*value as f64),
Attr::Float(value) => Some(*value),
_ => None,
};
match number(after) {
Some(after) => after > number(before).unwrap_or(0.0),
None => false,
}
}
enum UrlResolver<M> {
Record(RecordUrl),
Model(ModelUrl<M>),
Template(String),
}
enum Affects<M> {
Urls(Vec<String>),
Model(ModelUrls<M>),
}
enum SetValue<M> {
Fixed(Attr),
Model(Arc<dyn Fn(&M) -> Attr + Send + Sync>),
}
pub struct Registration<M: Model> {
conditions: Vec<Condition>,
url: Option<UrlResolver<M>>,
previous_url: Option<RecordUrl>,
affects: Vec<Affects<M>>,
ignoring: Vec<String>,
sets: Option<(String, SetValue<M>)>,
publishes_at: Option<String>,
changes_at: Option<String>,
policy: Option<Arc<dyn Policy<M>>>,
marker: PhantomData<fn(&M)>,
}
impl<M: Model> Default for Registration<M> {
fn default() -> Self {
Self {
conditions: Vec::new(),
url: None,
previous_url: None,
affects: Vec::new(),
ignoring: Vec::new(),
sets: None,
publishes_at: None,
changes_at: None,
policy: None,
marker: PhantomData,
}
}
}
impl<M: Model> Registration<M> {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn url(mut self, resolver: impl Fn(&Record) -> Option<String> + Send + Sync + 'static) -> Self {
self.url = Some(UrlResolver::Record(Arc::new(resolver)));
self
}
#[must_use]
pub fn url_template(mut self, template: impl Into<String>) -> Self {
self.url = Some(UrlResolver::Template(template.into()));
self
}
#[must_use]
pub fn url_for_model(mut self, resolver: impl Fn(&M) -> Option<String> + Send + Sync + 'static) -> Self {
self.url = Some(UrlResolver::Model(Arc::new(resolver)));
self
}
#[must_use]
pub fn previous_url(mut self, resolver: impl Fn(&Record) -> Option<String> + Send + Sync + 'static) -> Self {
self.previous_url = Some(Arc::new(resolver));
self
}
#[must_use]
pub fn policy(mut self, policy: impl Policy<M>) -> Self {
self.policy = Some(Arc::new(policy));
self
}
#[must_use]
pub fn when(self, attribute: &str) -> Self {
self.push(Condition::Truthy(attribute.to_owned()))
}
#[must_use]
pub fn when_holds(self, attribute: &str, value: impl Into<Attr>) -> Self {
self.push(Condition::Holds {
attribute: attribute.to_owned(),
values: vec![value.into()],
})
}
#[must_use]
pub fn when_in<V: Into<Attr>>(self, attribute: &str, values: impl IntoIterator<Item = V>) -> Self {
self.push(Condition::Holds {
attribute: attribute.to_owned(),
values: values.into_iter().map(Into::into).collect(),
})
}
#[must_use]
pub fn when_all<V: Into<Attr>>(mut self, conditions: impl IntoIterator<Item = (&'static str, V)>) -> Self {
for (attribute, value) in conditions {
self = self.when_holds(attribute, value);
}
self
}
#[must_use]
pub fn when_compare(self, attribute: &str, op: Op, value: impl Into<Attr>) -> Self {
self.push(Condition::Compare {
attribute: attribute.to_owned(),
op,
value: value.into(),
})
}
#[must_use]
pub fn when_not(self, attribute: &str) -> Self {
self.push(Condition::Falsy(attribute.to_owned()))
}
#[must_use]
pub fn when_not_holds(self, attribute: &str, value: impl Into<Attr>) -> Self {
self.when_compare(attribute, Op::Ne, value)
}
#[must_use]
pub fn when_fn(self, predicate: impl Fn(&Record) -> bool + Send + Sync + 'static) -> Self {
self.push(Condition::Predicate(Arc::new(predicate)))
}
#[must_use]
pub fn when_was(self, attribute: &str, value: impl Into<Attr>) -> Self {
self.push(Condition::Was {
attribute: attribute.to_owned(),
values: vec![value.into()],
})
}
#[must_use]
pub fn when_was_in<V: Into<Attr>>(self, attribute: &str, values: impl IntoIterator<Item = V>) -> Self {
self.push(Condition::Was {
attribute: attribute.to_owned(),
values: values.into_iter().map(Into::into).collect(),
})
}
#[must_use]
pub fn when_changed(self, attributes: &[&str]) -> Self {
self.push(Condition::Changed(
attributes.iter().map(|name| (*name).to_owned()).collect(),
))
}
#[must_use]
pub fn when_became(self, attribute: &str, value: impl Into<Attr>) -> Self {
self.push(Condition::Became {
attribute: attribute.to_owned(),
values: vec![value.into()],
})
}
#[must_use]
pub fn when_became_in<V: Into<Attr>>(self, attribute: &str, values: impl IntoIterator<Item = V>) -> Self {
self.push(Condition::Became {
attribute: attribute.to_owned(),
values: values.into_iter().map(Into::into).collect(),
})
}
#[must_use]
pub fn when_became_from(self, attribute: &str, to: impl Into<Attr>, from: impl Into<Attr>) -> Self {
self.push(Condition::BecameFrom {
attribute: attribute.to_owned(),
to: vec![to.into()],
from: vec![from.into()],
})
}
#[must_use]
pub fn when_left(self, attribute: &str, value: impl Into<Attr>) -> Self {
self.push(Condition::Left {
attribute: attribute.to_owned(),
values: vec![value.into()],
})
}
#[must_use]
pub fn when_left_in<V: Into<Attr>>(self, attribute: &str, values: impl IntoIterator<Item = V>) -> Self {
self.push(Condition::Left {
attribute: attribute.to_owned(),
values: values.into_iter().map(Into::into).collect(),
})
}
#[must_use]
pub fn when_increments(self, attribute: &str) -> Self {
self.push(Condition::Increments(attribute.to_owned()))
}
#[must_use]
pub fn sets(self, attribute: &str) -> Self {
self.sets_value(attribute, true)
}
#[must_use]
pub fn sets_value(mut self, attribute: &str, value: impl Into<Attr>) -> Self {
self.sets = Some((attribute.to_owned(), SetValue::Fixed(value.into())));
self
}
#[must_use]
pub fn sets_with(mut self, attribute: &str, value: impl Fn(&M) -> Attr + Send + Sync + 'static) -> Self {
self.sets = Some((attribute.to_owned(), SetValue::Model(Arc::new(value))));
self
}
#[must_use]
pub fn publishes_at(mut self, column: &str) -> Self {
self.publishes_at = Some(column.to_owned());
self
}
#[must_use]
pub fn changes_at(mut self, column: &str) -> Self {
self.changes_at = Some(column.to_owned());
self
}
#[must_use]
pub fn ignoring<S: AsRef<str>>(mut self, attributes: impl IntoIterator<Item = S>) -> Self {
self.ignoring = attributes.into_iter().map(|name| name.as_ref().to_owned()).collect();
self
}
#[must_use]
pub fn affects(mut self, resolver: impl Fn(&M) -> Vec<String> + Send + Sync + 'static) -> Self {
self.affects.push(Affects::Model(Arc::new(resolver)));
self
}
#[must_use]
pub fn affects_urls<S: Into<String>>(mut self, urls: impl IntoIterator<Item = S>) -> Self {
self.affects
.push(Affects::Urls(urls.into_iter().map(Into::into).collect()));
self
}
fn push(mut self, condition: Condition) -> Self {
self.conditions.push(condition);
self
}
pub fn has_url(&self) -> bool {
self.url.is_some() || self.policy.is_some()
}
pub fn publish_column(&self) -> Option<&str> {
self.publishes_at.as_deref()
}
pub fn change_column(&self) -> Option<&str> {
self.changes_at.as_deref()
}
pub fn url_of(&self, model: &M, record: &Record) -> laravel::Result<Option<String>> {
match &self.url {
Some(UrlResolver::Record(resolver)) => Ok(resolver(record)),
Some(UrlResolver::Model(resolver)) => Ok(resolver(model)),
Some(UrlResolver::Template(template)) => Ok(fill(template, record)),
None => match &self.policy {
Some(policy) => Ok(policy.url(model)),
None => Err(laravel::Error::msg(format!(
"No IndexNow URL resolver defined for [{}]. Call url() on the registration or give it a policy.",
M::META.name
))),
},
}
}
pub fn previous_url_of(&self, before: &Record) -> Option<String> {
match &self.url {
Some(UrlResolver::Record(resolver)) => resolver(before),
Some(UrlResolver::Template(template)) => fill(template, before),
_ => self
.previous_url
.as_ref()
.and_then(|resolver| resolver(before))
.or_else(|| self.policy.as_ref().and_then(|policy| policy.previous_url(before))),
}
}
pub fn affected_urls(&self, model: &M) -> Vec<String> {
let mut urls: Vec<String> = Vec::new();
for affects in &self.affects {
match affects {
Affects::Urls(list) => urls.extend(list.iter().cloned()),
Affects::Model(resolver) => urls.extend(resolver(model)),
}
}
if self.affects.is_empty()
&& let Some(policy) = &self.policy
{
urls.extend(policy.affects(model));
}
urls.retain(|url| !url.is_empty());
urls
}
pub fn passes(&self, record: &Record) -> bool {
self.conditions
.iter()
.filter(|condition| condition.is_state())
.all(|condition| condition.holds_for(record))
&& self.policy.as_ref().is_none_or(|policy| policy.when(record))
}
pub fn has_transitions(&self) -> bool {
self.conditions.iter().any(|condition| !condition.is_state())
}
pub fn decide(&self, change: &Change<'_>) -> Option<bool> {
if !self.has_transitions() {
return None;
}
Some(
self.conditions
.iter()
.all(|condition| condition.holds_for_change(change))
&& self.policy.as_ref().is_none_or(|policy| policy.when(change.after)),
)
}
pub fn ignored_attributes(&self) -> Vec<String> {
if !self.ignoring.is_empty() {
return self.ignoring.clone();
}
self.policy.as_ref().map(|policy| policy.ignoring()).unwrap_or_default()
}
pub fn has_sets(&self) -> bool {
self.sets.is_some()
}
pub async fn apply_set(&self, model: &M) -> laravel::Result<()> {
let Some((attribute, value)) = &self.sets else {
return Ok(());
};
let value = match value {
SetValue::Fixed(value) => value.clone(),
SetValue::Model(resolve) => resolve(model),
};
let values = match value {
Attr::Null => Values::new().set(attribute, None::<String>),
Attr::Bool(value) => Values::new().set(attribute, value),
Attr::Int(value) => Values::new().set(attribute, value),
Attr::Float(value) => Values::new().set(attribute, value),
Attr::Text(value) => Values::new().set(attribute, value),
Attr::Time(value) => Values::new().set(attribute, value),
};
laravel::model::__query::<M>()
.filter(M::META.key.eq(M::META.key.get(model).clone()))
.update_values(values)
.await?;
Ok(())
}
pub fn describe(&self) -> String {
let mut parts: Vec<String> = Vec::new();
if self.policy.is_some() {
parts.push("policy".to_owned());
}
parts.extend(self.conditions.iter().map(|condition| condition.name().to_owned()));
if self.publishes_at.is_some() {
parts.push("publishesAt".to_owned());
}
if parts.is_empty() {
"no conditions".to_owned()
} else {
parts.join(", ")
}
}
}
fn fill(template: &str, record: &Record) -> Option<String> {
let mut url = String::with_capacity(template.len());
let mut rest = template;
while let Some(start) = rest.find('{') {
let end = rest[start..].find('}')? + start;
let name = &rest[start + 1..end];
let part = record.get(name).to_url_part().filter(|part| !part.is_empty())?;
url.push_str(&rest[..start]);
url.push_str(&encode(&part));
rest = &rest[end + 1..];
}
url.push_str(rest);
Some(url)
}
fn encode(part: &str) -> String {
let mut encoded = String::with_capacity(part.len());
for byte in part.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
encoded.push(char::from(byte));
} else {
encoded.push_str(&format!("%{byte:02X}"));
}
}
encoded
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_template_is_filled_from_the_record() {
let record = Record::new().with("slug", "hello world").with("id", 7_i64);
assert_eq!(
fill("https://example.com/{id}/{slug}", &record),
Some("https://example.com/7/hello%20world".to_owned())
);
}
#[test]
fn a_template_with_a_missing_column_gives_no_url() {
let record = Record::new().with("slug", Attr::Null);
assert_eq!(fill("https://example.com/{slug}", &record), None);
assert_eq!(fill("https://example.com/{missing}", &record), None);
}
#[test]
fn values_compare_the_way_the_php_package_does() {
assert!(Attr::from(1_i64).matches(&Attr::from(true)));
assert!(Attr::from("1").matches(&Attr::from(true)));
assert!(!Attr::from("yes").matches(&Attr::from(true)));
assert!(!Attr::Null.matches(&Attr::from(false)));
assert!(Attr::from(3_i64).matches(&Attr::from(3.0)));
assert!(!Attr::from("3").matches(&Attr::from(3_i64)));
}
#[test]
fn truth_is_read_the_way_php_reads_it() {
assert!(Attr::from(5_i64).truthy());
assert!(Attr::from("a").truthy());
assert!(!Attr::from("0").truthy());
assert!(!Attr::from("").truthy());
assert!(!Attr::from(0_i64).truthy());
assert!(!Attr::Null.truthy());
}
#[test]
fn ordering_something_against_nothing_has_no_answer() {
assert!(!compares(&Attr::Null, Op::Gt, &Attr::from(1_i64)));
assert!(compares(&Attr::from(5_i64), Op::Gte, &Attr::from(5_i64)));
assert!(compares(&Attr::from("b"), Op::Gt, &Attr::from("a")));
}
}