laraindexnow 0.1.2

IndexNow for Laravel Rust: tell Bing, Yandex and other search engines a URL changed, the moment it changes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
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::tracked::instant;
use crate::value::Attr;

/// The operators `when_compare` understands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Op {
    /// Equal.
    Eq,
    /// Not equal.
    Ne,
    /// Greater than.
    Gt,
    /// Greater than or equal.
    Gte,
    /// Less than.
    Lt,
    /// Less than or equal.
    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",
        }
    }

    /// Whether the condition asks about the record as it stands, rather than about the change.
    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>),
}

/// How one model is tracked: where its URL is, when it belongs in the index, and what a write to
/// it leaves out of date.
///
/// Create one with [`track`](crate::track) and hand it to
/// [`IndexNowServiceProvider::track`](crate::IndexNowServiceProvider::track). Tracking the same
/// model twice gives two registrations, which combine with OR: a write is submitted when any of
/// them wants it. The conditions of one registration combine with AND.
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> {
    /// An empty registration. Prefer [`track`](crate::track).
    pub fn new() -> Self {
        Self::default()
    }

    /// The canonical URL of the record, read from its state. Because it reads a [`Record`], the
    /// same closure also resolves the address the record had *before* a write, so a changed slug
    /// announces both the old and the new URL. Return `None` and it is never submitted.
    #[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
    }

    /// The canonical URL as a template whose `{column}` placeholders are filled from the record,
    /// such as `https://example.com/blog/{slug}`. Like [`url`](Self::url), it also resolves the
    /// previous address. A placeholder naming an empty or missing column gives no URL.
    #[must_use]
    pub fn url_template(mut self, template: impl Into<String>) -> Self {
        self.url = Some(UrlResolver::Template(template.into()));

        self
    }

    /// The canonical URL, read from the typed model. It sees the model as it is after the write
    /// only, so use [`previous_url`](Self::previous_url) to announce the address that went away.
    #[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
    }

    /// The address a record had before a write, for registrations that resolve the URL from the
    /// typed model.
    #[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
    }

    /// Use a [`Policy`] for the URL and any rule the chain leaves out.
    #[must_use]
    pub fn policy(mut self, policy: impl Policy<M>) -> Self {
        self.policy = Some(Arc::new(policy));

        self
    }

    /// The attribute holds something true, read the way PHP reads it: `1`, `"1"` and `true` pass,
    /// `0`, `"0"`, `""` and null do not. A counter passes when it is above zero.
    #[must_use]
    pub fn when(self, attribute: &str) -> Self {
        self.push(Condition::Truthy(attribute.to_owned()))
    }

    /// The attribute holds this value.
    #[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()],
        })
    }

    /// The attribute holds any of these values.
    #[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(),
        })
    }

    /// Several attributes hold their values at once, as in
    /// `when_all([("status", "published"), ("review", "correct")])`.
    #[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
    }

    /// The attribute, compared with an operator.
    #[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(),
        })
    }

    /// The attribute holds something false.
    #[must_use]
    pub fn when_not(self, attribute: &str) -> Self {
        self.push(Condition::Falsy(attribute.to_owned()))
    }

    /// The attribute holds anything but this value.
    #[must_use]
    pub fn when_not_holds(self, attribute: &str, value: impl Into<Attr>) -> Self {
        self.when_compare(attribute, Op::Ne, value)
    }

    /// A closure judges the whole record. It is asked about the state before and after a write,
    /// so it reads a [`Record`] rather than the typed model.
    #[must_use]
    pub fn when_fn(self, predicate: impl Fn(&Record) -> bool + Send + Sync + 'static) -> Self {
        self.push(Condition::Predicate(Arc::new(predicate)))
    }

    /// The value the attribute held before this write.
    #[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()],
        })
    }

    /// Any of several previous values.
    #[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(),
        })
    }

    /// Any of these attributes changed, whatever their values. With none named, anything changed.
    #[must_use]
    pub fn when_changed(self, attributes: &[&str]) -> Self {
        self.push(Condition::Changed(
            attributes.iter().map(|name| (*name).to_owned()).collect(),
        ))
    }

    /// The attribute just took this value, having held something else.
    #[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()],
        })
    }

    /// The attribute just took any of these values.
    #[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(),
        })
    }

    /// The exact transition, both ends pinned down.
    #[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()],
        })
    }

    /// The attribute stopped holding this value.
    #[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()],
        })
    }

    /// The attribute stopped holding any of these values.
    #[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(),
        })
    }

    /// A numeric attribute went up, whatever the amount.
    #[must_use]
    pub fn when_increments(self, attribute: &str) -> Self {
        self.push(Condition::Increments(attribute.to_owned()))
    }

    /// Write `true` on the record once its URL has been handed over. Put the same attribute in the
    /// conditions and the record drops out the moment it is marked, which is how you say "submit
    /// this once, ever".
    #[must_use]
    pub fn sets(self, attribute: &str) -> Self {
        self.sets_value(attribute, true)
    }

    /// Write a value on the record once its URL has been handed over.
    #[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
    }

    /// Write a value computed from the record once its URL has been handed over.
    #[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
    }

    /// The column that holds the moment the record goes public. It makes the registration a
    /// source for `indexnow:due`, so scheduled content is announced when its date passes.
    #[must_use]
    pub fn publishes_at(mut self, column: &str) -> Self {
        self.publishes_at = Some(column.to_owned());

        self
    }

    /// The column that holds the last content change. Needs [`publishes_at`](Self::publishes_at).
    #[must_use]
    pub fn changes_at(mut self, column: &str) -> Self {
        self.changes_at = Some(column.to_owned());

        self
    }

    /// Attributes whose change is not a content change.
    #[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
    }

    /// Other URLs this write left out of date, computed from the model.
    #[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
    }

    /// Other URLs this write left out of date, as a fixed list.
    #[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
    }

    /// Whether the registration can resolve a URL: it has a resolver or a policy.
    pub fn has_url(&self) -> bool {
        self.url.is_some() || self.policy.is_some()
    }

    /// The column named by `publishes_at`.
    pub fn publish_column(&self) -> Option<&str> {
        self.publishes_at.as_deref()
    }

    /// The column named by `changes_at`.
    pub fn change_column(&self) -> Option<&str> {
        self.changes_at.as_deref()
    }

    /// The canonical URL of a record, or `None` when it has none.
    ///
    /// # Errors
    ///
    /// Fails when the registration has neither a URL resolver nor a policy.
    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
                ))),
            },
        }
    }

    /// The address a record had before a write, when it can be resolved.
    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))),
        }
    }

    /// The URLs a write to this record left out of date besides its own.
    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
    }

    /// Whether the record belongs in the index as it stands.
    pub fn passes(&self, record: &Record) -> bool {
        self.is_published(record)
            && 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))
    }

    /// Whether the publication date declared with `publishes_at` has arrived. A record with no
    /// date, or with one still ahead, is not public yet: `indexnow:due` announces it when the date
    /// comes, so a scheduled post is neither submitted on save nor listed by `indexnow:sync`.
    pub fn is_published(&self, record: &Record) -> bool {
        let Some(column) = &self.publishes_at else {
            return true;
        };

        instant(record.get(column)).is_some_and(|at| at <= laravel::now().timestamp())
    }

    /// Whether the registration has a condition that needs both states of a write.
    pub fn has_transitions(&self) -> bool {
        self.conditions.iter().any(|condition| !condition.is_state())
    }

    /// What a transition rule says about a write, or `None` when the registration has none and
    /// the default rule applies.
    pub fn decide(&self, change: &Change<'_>) -> Option<bool> {
        if !self.has_transitions() {
            return None;
        }

        Some(
            self.is_published(change.after)
                && self
                    .conditions
                    .iter()
                    .all(|condition| condition.holds_for_change(change))
                && self.policy.as_ref().is_none_or(|policy| policy.when(change.after)),
        )
    }

    /// Attributes whose change is not a content change, from the registration or its policy.
    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()
    }

    /// Whether the registration writes an attribute once a URL has been handed over.
    pub fn has_sets(&self) -> bool {
        self.sets.is_some()
    }

    /// Write the `sets` attribute on the record, quietly: no hooks and no model events, because a
    /// normal save would fire another event and the record, having just left the conditions,
    /// would be submitted a second time.
    ///
    /// # Errors
    ///
    /// Fails when the database rejects the write.
    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(())
    }

    /// A short description of how the registration is configured, for `indexnow:models`.
    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(", ")
        }
    }
}

/// Fill the `{column}` placeholders of a URL template from a record.
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")));
    }
}