laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
use laravel::Application;
use laravel::config::Env;
use laravel::http::Json;
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::time::civil::Date;
use laravel::validation::{Rule, Rules, Valid, Validate};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::validation::errors;

fn comparison(name: &str, other: &str) -> Rule {
    match name {
        "after" => Rule::after(other),
        "after_or_equal" => Rule::after_or_equal(other),
        "before" => Rule::before(other),
        "before_or_equal" => Rule::before_or_equal(other),
        _ => unreachable!(),
    }
}

#[tokio::test]
async fn calendar_rules_match_classic_or_the_explicit_date_policy() {
    let fixtures: Vec<Value> = serde_json::from_str(include_str!("fixtures/validation-dates.json")).unwrap();
    let mut failures = Vec::new();
    for fixture in fixtures {
        let name = fixture["rule"].as_str().unwrap();
        let rule = if name == "date" {
            Rule::date()
        } else {
            comparison(name, "starts_on")
        };
        let mut rules = Rules::new()
            .field("event_date", [rule])
            .label("event_date", "Event date")
            .label("starts_on", "Start date");
        if fixture["nullable"] == true {
            rules = rules.nullable("event_date");
        }
        let actual = errors(rules, fixture["input"].clone()).await;
        let expected = fixture.get("expected_errors").unwrap_or(&fixture["errors"]);
        if actual != *expected {
            failures.push(format!("{name} {}: {actual} != {expected}", fixture["input"]));
        }
    }
    assert!(failures.is_empty(), "{}", failures.join("\n"));
}

#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Booking {
    #[serde(alias = "arrival")]
    #[validate(required, date, label = "arrival date")]
    starts_on: Date,
    #[validate(required, date, after_or_equal("starts_on"), label = "departure date")]
    ends_on: Date,
    #[validate(before("starts_on"))]
    earlier: Option<Date>,
    #[validate(after("ends_on"))]
    later: Option<Date>,
    #[validate(before_or_equal("ends_on"))]
    cutoff: Option<Date>,
    #[serde(default)]
    #[validate(each(
        date,
        after_or_equal("starts_on"),
        label = "visit date",
        messages(
            date = "Visit :position needs a calendar date.",
            after_or_equal = "Visit :position must be on or after :date."
        )
    ))]
    visits: Vec<Option<Date>>,
}

#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Itinerary {
    starts_on: Date,
    #[validate]
    primary: Booking,
    #[validate]
    bookings: Vec<Booking>,
}

#[derive(Deserialize, Serialize, Validate)]
struct Limits {
    #[validate(date, label = "booking deadline")]
    deadline: Date,
}

#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Offer {
    #[serde(alias = "policy")]
    #[validate]
    limits: Limits,
    #[validate(
        before_or_equal("limits.deadline"),
        messages(before_or_equal = "Meet :date (:other).")
    )]
    ends_on: Date,
}

#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct DefaultDates {
    #[serde(default)]
    starts_on: Date,
    #[validate(after_or_equal("starts_on"))]
    ends_on: Date,
}

fn app() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.api(|route: &mut Router| {
                route.post("/bookings", |Valid(input): Valid<Booking>| async move {
                    let year = input.starts_on.year();
                    Json(json!({"booking": input, "year": year}))
                });
                route.post("/itineraries", |Valid(input): Valid<Itinerary>| async { Json(input) });
                route.post("/offers", |Valid(input): Valid<Offer>| async { Json(input) });
                route.post("/defaults", |Valid(input): Valid<DefaultDates>| async { Json(input) });
            });
        })
        .create()
}

#[tokio::test]
async fn json_and_form_dates_decode_to_jiff_and_serialize_as_calendar_strings() {
    let app = app();
    let response = app
        .post("/api/bookings")
        .json(json!({"starts_on": "2024-02-29", "ends_on": "2024-02-29",
            "earlier": "2024-02-28", "later": "2024-03-01", "cutoff": "2024-02-29",
            "visits": [null, "2024-02-29", "2024-03-01"]}))
        .await;
    response.assert_ok();
    assert_eq!(response.json()["year"], 2024);
    assert_eq!(response.json()["booking"]["starts_on"], "2024-02-29");
    assert_eq!(
        response.json()["booking"]["visits"],
        json!([null, "2024-02-29", "2024-03-01"])
    );

    let response = app
        .post("/api/bookings")
        .form([
            ("arrival", " 0001-01-01 "),
            ("ends_on", "9999-12-31"),
            ("earlier", ""),
            ("later", " "),
            ("visits[7]", "2000-02-29"),
            ("visits[9]", ""),
        ])
        .await;
    response.assert_ok();
    assert_eq!(response.json()["year"], 1);
    assert_eq!(response.json()["booking"]["starts_on"], "0001-01-01");
    assert_eq!(response.json()["booking"]["ends_on"], "9999-12-31");
    assert_eq!(response.json()["booking"]["earlier"], Value::Null);
    assert_eq!(response.json()["booking"]["later"], Value::Null);
    assert_eq!(response.json()["booking"]["visits"], json!(["2000-02-29", null]));
}

#[tokio::test]
async fn malformed_dates_use_date_messages_and_preserve_nullable_and_required_checks() {
    let app = app();
    for value in [
        json!("2023-02-29"),
        json!("2024-04-31"),
        json!("2024-02-29T00:00:00Z"),
        json!("2024-2-9"),
        json!("02/29/2024"),
        json!("0000-01-01"),
        json!(false),
        json!(20240229),
        json!("tomorrow"),
        json!("2024-02-29"),
        json!(["2024-02-29"]),
    ] {
        let response = app
            .post("/api/bookings")
            .json(json!({"starts_on": "2024-02-29", "ends_on": value}))
            .await;
        response.assert_status(422);
        response.assert_nothing_reported();
        let expected = if value == "2024-02-29T00:00:00Z" {
            json!({"ends_on": [
                "The departure date field must be a valid date.",
                "The departure date field must be a date after or equal to arrival date."
            ]})
        } else {
            json!({"ends_on": ["The departure date field must be a valid date."]})
        };
        assert_eq!(response.json()["errors"], expected);
    }
    let response = app
        .post("/api/bookings")
        .json(json!({"starts_on": null, "ends_on": null}))
        .await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({
            "starts_on": ["The arrival date field is required."], "ends_on": ["The departure date field is required."]
        })
    );
    let response = app
        .post("/api/bookings")
        .json(
            json!({"starts_on": "2024-02-29", "ends_on": "2024-02-29", "earlier": null,
            "later": null, "cutoff": null, "visits": [null]}),
        )
        .await;
    response.assert_ok();
}

#[tokio::test]
async fn comparisons_use_classic_wording_and_custom_messages_at_original_sparse_keys() {
    let response = app()
        .post("/api/bookings")
        .form([
            ("arrival", "2024-02-29"),
            ("ends_on", "2024-02-28"),
            ("earlier", "2024-02-29"),
            ("later", "2024-02-28"),
            ("cutoff", "2024-02-29"),
            ("visits[7]", "2024-02-28"),
            ("visits[9]", "2023-02-29"),
        ])
        .await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({
            "ends_on": ["The departure date field must be a date after or equal to arrival date."],
            "earlier": ["The earlier field must be a date before arrival date."],
            "later": ["The later field must be a date after departure date."],
            "cutoff": ["The cutoff field must be a date before or equal to departure date."],
            "visits.7": ["Visit 8 must be on or after arrival date."],
            "visits.9": ["Visit 10 needs a calendar date."]
        })
    );
}

#[tokio::test]
async fn nested_bookings_and_sparse_entries_use_their_own_date_references() {
    let app = app();
    let response = app
        .post("/api/itineraries")
        .json(json!({"starts_on": "9999-12-31",
        "primary": {"starts_on": "2024-02-28", "ends_on": "2024-02-29"},
        "bookings": [{"starts_on": "2000-02-29", "ends_on": "2000-03-01"}]}))
        .await;
    response.assert_ok();
    let response = app
        .post("/api/itineraries")
        .form([
            ("starts_on", "9999-12-31"),
            ("primary[arrival]", "2024-02-28"),
            ("primary[ends_on]", "2024-02-29"),
            ("bookings[2][arrival]", "2024-02-28"),
            ("bookings[2][ends_on]", "2024-02-29"),
            ("bookings[7][arrival]", "2024-03-01"),
            ("bookings[7][ends_on]", "2024-02-29"),
            ("bookings[7][visits][3]", "2024-02-29"),
        ])
        .await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({
            "bookings.7.ends_on": ["The departure date field must be a date after or equal to arrival date."],
            "bookings.7.visits.3": ["Visit 8 must be on or after arrival date."]
        })
    );
}

#[tokio::test]
async fn dotted_references_resolve_parent_aliases_and_labels_and_primary_names_win() {
    let response = app()
        .post("/api/offers")
        .form([("policy[deadline]", "2024-02-29"), ("ends_on", "2024-03-01")])
        .await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({"ends_on": ["Meet booking deadline (booking deadline)."]})
    );
    let input = json!({"starts_on": "2024-02-28", "arrival": "2024-03-01", "ends_on": "2024-02-29"});
    assert_eq!(errors(Booking::declared_rules(), input).await, json!({}));
    let input = json!({"limits": {"deadline": "2024-03-01"}, "policy": {"deadline": "2024-02-28"},
        "ends_on": "2024-02-29"});
    assert_eq!(errors(Offer::declared_rules(), input).await, json!({}));
}

#[tokio::test]
async fn references_are_required_calendar_values_never_defaults_or_literal_dates() {
    for rule in ["after", "after_or_equal", "before", "before_or_equal"] {
        for reference in [
            None,
            Some(json!(null)),
            Some(json!("")),
            Some(json!(false)),
            Some(json!(true)),
            Some(json!([])),
            Some(json!({"date": "2024-02-29"})),
            Some(json!("2024-02-30")),
            Some(json!("2024-02-29T00:00:00Z")),
            Some(json!("tomorrow")),
        ] {
            let mut input = json!({"value": "2024-02-29"});
            if let Some(reference) = reference {
                input["other"] = reference;
            }
            let rules = Rules::new()
                .field("value", [comparison(rule, "other")])
                .nullable("other")
                .label("other", "other date")
                .message("value", rule, "Compare with :date (:other).");
            assert_eq!(
                errors(rules, input).await,
                json!({"value": ["Compare with other date (other date)."]})
            );
        }
    }
    let rules = Rules::new().field("value", [Rule::after("2024-02-28")]);
    assert_ne!(errors(rules, json!({"value": "2024-02-29"})).await, json!({}));
    let rules = Rules::new().field("value", [Rule::before("2024-02-28")]);
    assert_eq!(
        errors(rules, json!({"value": "2024-02-29", "2024-02-28": "2024-03-01"})).await,
        json!({})
    );

    let response = app().post("/api/defaults").json(json!({"ends_on": "2024-02-29"})).await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({
            "ends_on": ["The ends on field must be a date after or equal to starts on."]
        })
    );
}

#[derive(Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "the test checks only the declared rules")]
struct Trip {
    #[validate(required, date, today_or_after, label = "departure date")]
    departs_on: Date,
}

#[tokio::test]
async fn today_rules_compare_with_todays_date_in_utc() {
    use laravel::time::{Timestamp, ToSpan};

    let app = Application::configure().replace_env(Env::default()).create();
    app.travel_to("2026-11-19T23:30:00Z".parse::<Timestamp>().unwrap());
    let check = |rule: Rule, value: &'static str| {
        let app = app.clone();
        async move {
            app.scope(async || errors(Rules::new().field("day", [rule]), json!({ "day": value })).await)
                .await
        }
    };

    assert_eq!(check(Rule::after_today(), "2026-11-20").await, json!({}));
    assert_eq!(
        check(Rule::after_today(), "2026-11-19").await,
        json!({ "day": ["The day field must be a date after today."] })
    );
    assert_eq!(check(Rule::today_or_after(), "2026-11-19").await, json!({}));
    assert_eq!(
        check(Rule::today_or_after(), "2026-11-18").await,
        json!({ "day": ["The day field must be a date after or equal to today."] })
    );
    assert_eq!(check(Rule::before_today(), "2026-11-18").await, json!({}));
    assert_eq!(
        check(Rule::before_today(), "2026-11-19").await,
        json!({ "day": ["The day field must be a date before today."] })
    );
    assert_eq!(check(Rule::today_or_before(), "2026-11-19").await, json!({}));
    assert_eq!(
        check(Rule::today_or_before(), "2026-11-20").await,
        json!({ "day": ["The day field must be a date before or equal to today."] })
    );

    // A timestamp compares by its date in UTC, so 00:10 in Paris is still the 19th...
    assert_eq!(
        check(Rule::after_today(), "2026-11-20T00:10:00+01:00").await,
        json!({ "day": ["The day field must be a date after today."] })
    );
    assert_eq!(
        check(Rule::after_today(), "soon").await,
        json!({ "day": ["The day field must be a valid date."] })
    );

    app.travel(1.hours());
    assert_eq!(
        check(Rule::after_today(), "2026-11-20").await,
        json!({ "day": ["The day field must be a date after today."] })
    );
    let trip = app
        .scope(async || errors(Trip::declared_rules(), json!({ "departs_on": "2026-11-19" })).await)
        .await;
    assert_eq!(
        trip,
        json!({ "departs_on": ["The departure date field must be a date after or equal to today."] })
    );
}