cjtoolkit_structured_validator/common/validation_check.rs
1//! This module contains structures and traits for performing validation checks.
2
3use crate::common::locale::{ValidateErrorCollector, ValidateErrorStore};
4
5/// A trait for performing validation checks and handling validation-related errors.
6///
7/// This trait provides methods to:
8/// - Create a new validation error instance from an error store.
9/// - Collect and validate errors, returning a result depending on whether any errors are found.
10///
11/// # Associated Types
12/// - `Self`: The concrete type that implements the `ValidationCheck` trait, which represents validation errors.
13///
14/// # Required Methods
15///
16/// ## `validate_new`
17///
18/// Creates a new instance of the implementing type using a provided `ValidateErrorStore`.
19///
20/// ### Parameters
21/// - `messages`: An instance of `ValidateErrorStore` that holds validation error information.
22///
23/// ### Returns
24/// - `Self`: A new instance of the implementing type initialized with the given error messages.
25///
26///
27/// # Provided Methods
28///
29/// ## `validate_check`
30///
31/// Performs a validation check using a `ValidateErrorCollector`. If the collector contains errors,
32/// it returns an error wrapped in the implementing type; otherwise, it succeeds with `Ok(())`.
33///
34/// ### Parameters
35/// - `messages`: An instance of `ValidateErrorCollector` that holds collected validation errors.
36///
37/// ### Returns
38/// - `Ok(())`: If the collector does not contain any errors.
39/// - `Err(Self)`: If the collector contains errors, an error instance of the implementing type is returned.
40///
41/// The default implementation checks if the provided `messages` is empty. If it is empty, it returns an `Ok(())`.
42/// Otherwise, it converts the messages into a `ValidateErrorStore` and creates a new validation error instance using `validate_new`.
43///
44///
45pub trait ValidationCheck: Sized {
46 fn validate_new(messages: ValidateErrorStore) -> Self;
47
48 fn validate_check(messages: ValidateErrorCollector) -> Result<(), Self> {
49 if messages.is_empty() {
50 Ok(())
51 } else {
52 Err(Self::validate_new(messages.into()))
53 }
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60 use crate::base::string_rules::StringMandatoryLocale;
61
62 struct TestValidationCheck;
63
64 impl ValidationCheck for TestValidationCheck {
65 fn validate_new(_: ValidateErrorStore) -> Self {
66 Self
67 }
68 }
69
70 #[test]
71 fn test_validate_check_is_err() {
72 let mut messages = ValidateErrorCollector::new();
73 messages.push(("error".to_string(), Box::new(StringMandatoryLocale)));
74 assert!(TestValidationCheck::validate_check(messages).is_err());
75 }
76
77 #[test]
78 fn test_validate_check_is_ok() {
79 let messages = ValidateErrorCollector::new();
80 assert!(TestValidationCheck::validate_check(messages).is_ok());
81 }
82}