use std::borrow::Cow;
use php_std::pcre;
use php_std::value::numeric_str;
use crate::object::input::loose_str_eq;
use crate::object::{Error, Input, Type, Validator, Verdict, compose, is_valid_via_validate, network, scalar, text};
pub(crate) fn preg_matches(pattern: &[u8], subject: &[u8]) -> bool {
matches!(pcre::preg_match_bare(pattern, subject), Ok(p) if p.value == pcre::Value::Int(1))
}
fn php_int(n: usize) -> i64 {
i64::try_from(n).unwrap_or(i64::MAX)
}
#[derive(Debug, Clone)]
pub struct Text {
pub length: usize,
pub min: usize,
pub allow_list: Vec<Cow<'static, str>>,
pub require_non_blank: bool,
}
impl Text {
pub const NUMBERS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
pub const ALPHABET_UPPER: [&'static str; 26] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z",
];
pub const ALPHABET_LOWER: [&'static str; 26] = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z",
];
pub const fn new(length: usize) -> Self {
Self::with_min(length, 1)
}
pub const fn with_min(length: usize, min: usize) -> Self {
Self { length, min, allow_list: Vec::new(), require_non_blank: false }
}
pub fn with_allow_list<I, S>(mut self, list: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<Cow<'static, str>>,
{
self.allow_list = list.into_iter().map(Into::into).collect();
self
}
pub fn non_blank(mut self) -> Self {
self.require_non_blank = true;
self
}
fn accepts(&self, s: &[u8]) -> bool {
if self.require_non_blank && text::is_blank(s) {
return false;
}
if !text::text_length(s, php_int(self.min), php_int(self.length)) {
return false;
}
self.allow_list.is_empty()
|| s.chunks(1).all(|c| {
let numeric = std::str::from_utf8(c).ok().and_then(numeric_str).is_some();
self.allow_list.iter().any(|a| if numeric { loose_str_eq(c, a.as_bytes()) } else { c == a.as_bytes() })
})
}
}
impl Validator for Text {
fn description(&self) -> String {
let allow_list = (!self.allow_list.is_empty()).then(|| self.allow_list.join(", "));
let mut description = Vec::new();
text::text_description(
php_int(self.length),
php_int(self.min),
allow_list.as_deref().map(str::as_bytes),
self.require_non_blank,
&mut description,
);
String::from_utf8_lossy(&description).into_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(value.as_str().is_some_and(|s| self.accepts(s))))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Identifier {
pub length: usize,
}
impl Identifier {
pub const fn new(length: usize) -> Self {
Self { length }
}
}
impl Validator for Identifier {
fn description(&self) -> String {
let mut description = Vec::new();
text::identifier_description(php_int(self.length), &mut description);
String::from_utf8_lossy(&description).into_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(
value.as_str().is_some_and(|s| Text::with_min(self.length, 1).accepts(s) && text::identifier(s)),
))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone)]
pub struct Contains {
patterns: Vec<String>,
needles: Vec<Vec<u8>>,
strict: bool,
}
impl Contains {
pub fn new(patterns: Vec<String>, strict: bool) -> Result<Self, Error> {
if patterns.is_empty() {
return Err(Error::InvalidArgument("Patterns array cannot be empty".into()));
}
let needles =
patterns.iter().map(|p| if strict { p.as_bytes().to_vec() } else { text::lower(p.as_bytes()) }).collect();
Ok(Self { patterns, needles, strict })
}
pub fn patterns(&self) -> &[String] {
&self.patterns
}
}
impl Validator for Contains {
fn description(&self) -> String {
let mut description = Vec::new();
text::contains_description(self.patterns.join(", ").as_bytes(), self.strict, &mut description);
String::from_utf8_lossy(&description).into_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
let Some(s) = value.as_str() else {
return Ok(Verdict::INVALID);
};
let lowered;
let haystack = if self.strict {
s
} else {
lowered = text::lower(s);
&lowered
};
Ok(Verdict::of(self.needles.iter().any(|n| text::contains(haystack, n))))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Default)]
pub struct Globstar {
pub patterns: Vec<String>,
}
impl Globstar {
pub fn new(patterns: Vec<String>) -> Self {
Self { patterns }
}
fn matches(subject: &[u8], pattern: &[u8]) -> bool {
preg_matches(&compose::globstar_regex(pattern), subject)
}
}
fn exclusion(pattern: &[u8]) -> Option<&[u8]> {
compose::exclusion(pattern).then(|| &pattern[1..])
}
impl Validator for Globstar {
fn description(&self) -> String {
compose::GLOBSTAR_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
let Some(subject) = value.as_str() else {
return Ok(Verdict::INVALID);
};
if self.patterns.is_empty() {
return Ok(Verdict::VALID);
}
let patterns = || self.patterns.iter().map(|p| p.as_bytes());
if patterns().all(|p| exclusion(p).is_some()) {
return Ok(Verdict::of(patterns().all(|p| !Self::matches(subject, exclusion(p).unwrap_or(p)))));
}
if patterns().any(|p| exclusion(p).is_none() && !compose::wildcard(p) && Self::matches(subject, p)) {
return Ok(Verdict::VALID);
}
let mut state = false;
for p in patterns() {
match exclusion(p) {
Some(excluded) if Self::matches(subject, excluded) => state = false,
None if compose::wildcard(p) && Self::matches(subject, p) => state = true,
_ => {}
}
}
Ok(Verdict::of(state))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct HexColor;
impl Validator for HexColor {
fn description(&self) -> String {
"Value must be a valid Hex color code".to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(scalar::hex_color(value.scalar())))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Phone {
pub allow_empty: bool,
pub normalize: bool,
}
impl Phone {
pub fn normalize(value: &[u8]) -> Vec<u8> {
network::phone_normalize(value)
}
}
impl Validator for Phone {
fn description(&self) -> String {
network::PHONE_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
let Some(s) = value.as_str() else {
return Ok(Verdict::INVALID);
};
if self.allow_empty && s.is_empty() {
return Ok(Verdict::VALID);
}
Ok(Verdict::of(if self.normalize { network::phone(&Self::normalize(s)) } else { network::phone(s) }))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Wildcard;
impl Validator for Wildcard {
fn description(&self) -> String {
"Every input is valid".to_owned()
}
fn is_valid(&self, _value: &serde_json::Value) -> bool {
true
}
fn validate(&self, _value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::VALID)
}
fn kind(&self) -> Type {
Type::String
}
}