use std::sync::{Arc, Mutex};
use laravel::Application;
use laravel::config::{Env, session::Driver};
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::{Json, Request};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{
Field, InputValue, Rule, RuleError, Rules, Valid, Validate, ValidationError, ValidationRule,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::support::Invalid;
mod package {
use super::*;
pub struct Slug;
impl ValidationRule for Slug {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
match field.value.and_then(InputValue::as_str) {
Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()),
_ => Err(RuleError::invalid(format!("The {} field must be a slug.", field.name))),
}
}
}
pub struct StartsWith(&'static str);
impl StartsWith {
pub fn new() -> Self {
Self("")
}
pub fn prefix(mut self, prefix: &'static str) -> Self {
self.0 = prefix;
self
}
}
impl ValidationRule for StartsWith {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
if field
.value
.and_then(InputValue::as_str)
.is_some_and(|value| value.starts_with(self.0))
{
Ok(())
} else {
Err(RuleError::invalid(format!(
"The {} field must start with {}.",
field.name, self.0
)))
}
}
}
}
#[derive(Debug, Deserialize, Serialize, Validate)]
struct Item {
#[serde(alias = "title")]
#[validate(required, max_length = 5, package::Slug)]
name: String,
quantity: u32,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Order {
#[serde(alias = "products")]
#[validate(required, each)]
items: Vec<Item>,
#[validate(each(required, max_length = 5, package::Slug))]
tags: Vec<String>,
#[validate(package::StartsWith::new().prefix("order-"))]
reference: String,
}
async fn store(Valid(order): Valid<Order>) -> Json<Order> {
Json(order)
}
fn app() -> Application {
Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
})
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/orders", store);
});
routing.web(|route: &mut Router| {
route.post("/orders", store);
});
})
.create()
}
#[tokio::test]
async fn list_rules_collect_custom_builtin_and_decoding_errors() {
app().post("/api/orders")
.json(json!({
"items": [{"name":"rust", "quantity":1}, {"name":"TOO-LONG", "quantity":"many"}, {}],
"tags": ["rust", "UPPER", "", 42], "reference":"wrong"
}))
.await
.assert_status(422)
.assert_nothing_reported()
.assert_json(json!({"errors": {
"items.1.name": ["The items.1.name field must not be greater than 5 characters.", "The items.1.name field must be a slug."],
"items.1.quantity": ["The items.1.quantity field must be an integer."],
"items.2.name": ["The items.2.name field is required."],
"items.2.quantity": ["The items.2.quantity field is required."],
"tags.1": ["The tags.1 field must be a slug."],
"tags.2": ["The tags.2 field is required."],
"tags.3": ["The tags.3 field must be a string.", "The tags.3 field must be a slug."],
"reference": ["The reference field must start with order-."]
}}));
}
#[tokio::test]
async fn a_huge_list_of_failing_items_reports_only_the_first_thousand_fields() {
let response = app()
.post("/api/orders")
.json(json!({ "items": [{"name": "rust", "quantity": 1}], "tags": vec![""; 5_000], "reference": "order-one" }))
.await;
let errors = response.assert_status(422).json()["errors"]
.as_object()
.unwrap()
.clone();
assert_eq!(errors.len(), 1_000);
assert_eq!(errors["tags.999"], json!(["The tags.999 field is required."]));
assert!(!errors.contains_key("tags.1000"));
}
#[tokio::test]
async fn lists_accept_json_and_sparse_form_keys_with_aliases() {
let app = app();
app.post("/api/orders")
.json(json!({"items":[{"name":"rust", "quantity":1}], "tags":["rust"], "reference":" order-one "}))
.await
.assert_ok()
.assert_json(json!({"reference":"order-one"}));
app.post("/api/orders")
.form([
("products[7][title]", "UPPER"),
("products[7][quantity]", "1"),
("products[2][name]", "rust"),
("products[2][quantity]", "2"),
("tags[9]", "TOO-LONG"),
("reference", "order-one"),
])
.await
.assert_status(422)
.assert_invalid(&["products.7.title", "tags.9"])
.assert_valid(&["items.7.name", "products.2.name", "tags.0"]);
app.post("/api/orders")
.form([
("items[7][name]", "rust"),
("items[7][quantity]", "1"),
("tags[9]", "rust"),
("reference", "order-one"),
])
.await
.assert_ok()
.assert_json(json!({"items":[{"name":"rust", "quantity":1}], "tags":["rust"]}));
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Optional {
#[validate(each)]
items: Option<Vec<Option<Item>>>,
#[validate(each(required, max_length = 2))]
required_tags: Option<Vec<Option<String>>>,
#[validate(each(max_length = 2, package::Slug))]
tags: Option<Vec<Option<String>>>,
}
#[tokio::test]
async fn nullable_lists_and_entries_preserve_required_semantics() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/optional", |Valid(input): Valid<Optional>| async move { Json(input) });
});
})
.create();
for body in [
json!({}),
json!({"items":null, "tags":null}),
json!({"items":[], "tags":[]}),
json!({"items":[null], "tags":[null, "ok"]}),
] {
app.post("/api/optional").json(&body).await.assert_ok();
}
app.post("/api/optional")
.json(json!({"required_tags":[null, "", "abc"], "tags":[null, "ABC"]}))
.await
.assert_invalid(&["required_tags.0", "required_tags.1", "required_tags.2", "tags.1"])
.assert_valid(&["tags.0"])
.assert_json(json!({"errors": {
"required_tags.0": ["The required_tags.0 field is required."],
"required_tags.1": ["The required_tags.1 field is required."],
"required_tags.2": ["The required_tags.2 field must not be greater than 2 characters."],
"tags.1": ["The tags.1 field must not be greater than 2 characters.", "The tags.1 field must be a slug."]
}}));
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Node {
#[validate(required, max_length = 2)]
name: String,
#[serde(default)]
#[validate]
children: Vec<Node>,
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Batch<T> {
#[validate]
entries: Vec<T>,
}
impl<T: laravel::validation::Validate> laravel::validation::ValidatesRequest for Batch<T> {
async fn authorize(_: &laravel::http::Request) -> laravel::Result<bool> {
Ok(true)
}
}
#[tokio::test]
async fn malformed_lists_and_items_report_shapes_without_descendant_errors() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/nodes", |Valid(_): Valid<Batch<Node>>| async { "ok" });
});
})
.create();
for body in [json!({"entries":42}), json!({"entries":{"named":{"name":"ok"}}})] {
let response = app.post("/api/nodes").json(&body).await;
assert_eq!(
response.json()["errors"],
json!({"entries": ["The entries field must be an array."]})
);
}
let response = app
.post("/api/nodes")
.json(json!({"entries":[null, 42, [], {"name":"long"}]}))
.await;
assert_eq!(
response.json()["errors"],
json!({
"entries.0": ["The entries.0 field is required."],
"entries.1": ["The entries.1 field must be an array."],
"entries.2": ["The entries.2 field must be an array."],
"entries.3.name": ["The entries.3.name field must not be greater than 2 characters."]
})
);
}
type RecordedValues = Arc<Mutex<Vec<(String, Option<InputValue>)>>>;
struct Recording {
seen: RecordedValues,
implicit: bool,
fail: bool,
}
impl ValidationRule for Recording {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
self.seen
.lock()
.unwrap()
.push((field.name.to_owned(), field.value.cloned()));
if self.fail {
Err(RuleError::invalid("Rejected.".to_owned()))
} else {
Ok(())
}
}
fn implicit(&self) -> bool {
self.implicit
}
}
struct MatchesRoot;
impl ValidationRule for MatchesRoot {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
if field.input.get("expected") == field.value {
Ok(())
} else {
Err(RuleError::invalid(format!(
"The {} field must match expected.",
field.name
)))
}
}
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct MatchingItem {
#[serde(rename = "display", alias = "label")]
#[validate(MatchesRoot)]
name: String,
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validation is exercised")]
struct MatchingBatch {
#[validate(each)]
items: Vec<MatchingItem>,
}
#[tokio::test]
async fn nested_custom_rules_receive_original_paths_and_complete_input() {
let mut request = Request::from_http(
http::Request::post("/")
.header("content-type", "application/json")
.body(laravel::axum::body::Body::from(
json!({"expected":"ok", "items":[{"label":"bad"},{"display":"ok"}]}).to_string(),
))
.unwrap(),
);
request.load_input().await.unwrap();
let ValidationError::Invalid(errors) = request.validate::<MatchingBatch>().await.unwrap_err() else {
panic!("expected field errors");
};
assert_eq!(
serde_json::to_value(errors).unwrap(),
json!({"items.0.label":["The items.0.label field must match expected."]})
);
}
#[tokio::test]
async fn custom_rule_execution_and_list_paths_match_classic_fixtures() {
let fixtures: Vec<Value> = serde_json::from_str(include_str!("fixtures/validation-rules.json")).unwrap();
for fixture in fixtures {
let seen = Arc::new(Mutex::new(Vec::new()));
let mut rules = Rules::new();
if fixture["kind"] == "custom" {
if fixture["nullable"] == true {
rules = rules.nullable("value");
}
if fixture["required"] == true {
rules = rules.field("value", [Rule::required()]);
}
rules = rules.field(
"value",
(0..2).map(|_| {
Rule::custom(Recording {
seen: seen.clone(),
implicit: fixture["implicit"] == true,
fail: true,
})
}),
);
} else {
rules = rules.each::<Node>("items");
}
let errors = rules
.validate(fixture["input"].as_object().unwrap())
.await
.err()
.map(|error| error.invalid().clone())
.unwrap_or_default();
assert_eq!(
serde_json::to_value(errors).unwrap(),
fixture["errors"],
"{}",
fixture["name"]
);
if fixture["kind"] == "custom" {
for (name, value) in seen.lock().unwrap().iter() {
assert_eq!(
value,
&fixture["input"].get(name).cloned().map(InputValue::from),
"{}",
fixture["name"]
);
}
let calls: Vec<_> = seen.lock().unwrap().iter().map(|(name, _)| name.clone()).collect();
assert_eq!(
serde_json::to_value(calls).unwrap(),
fixture["calls"],
"{}",
fixture["name"]
);
}
}
}