use std::borrow::Cow;
use php_std::string::strtolower;
use php_std::{Str, Value};
use crate::object::input::{View, loose_str_eq};
use crate::object::{Error, Input, Type, Validator, Verdict, compose, is_valid_via_validate, text};
#[derive(Debug, Clone)]
pub struct WhiteList {
list: Vec<Value>,
strict: bool,
kind: Type,
}
impl WhiteList {
pub fn new(list: &[&str]) -> Self {
let list = list.iter().map(|s| Value::Str(Str::from(strtolower(s.as_bytes()).into_owned()))).collect();
Self { list, strict: false, kind: Type::String }
}
pub fn strict(list: &[&str]) -> Self {
Self { list: list.iter().map(|s| Value::Str(Str::from(*s))).collect(), strict: true, kind: Type::String }
}
pub fn with(list: Vec<Value>, strict: bool, kind: Type) -> Result<Self, Error> {
let list = if strict {
list
} else {
list.iter()
.map(|v| Ok(Value::Str(Str::from(strtolower(&Input::Value(v).to_bytes()?).into_owned()))))
.collect::<Result<_, Error>>()?
};
Ok(Self { list, strict, kind })
}
pub fn list(&self) -> &[Value] {
&self.list
}
}
fn identical(a: Input<'_>, b: Input<'_>) -> bool {
match (a.view(), b.view()) {
(View::Null, View::Null) => true,
(View::Bool(x), View::Bool(y)) => x == y,
(View::Int(x), View::Int(y)) => x == y,
(View::Float(x), View::Float(y)) => x == y,
(View::Str(x), View::Str(y)) => x == y,
(View::Array(x), View::Array(y)) => {
x.len() == y.len() && x.zip(y).all(|((kx, vx), (ky, vy))| kx == ky && identical(vx, vy))
}
_ => false,
}
}
impl Validator for WhiteList {
fn description(&self) -> String {
let items: Vec<Vec<u8>> =
self.list.iter().map(|v| Input::Value(v).to_bytes().map(Cow::into_owned).unwrap_or_default()).collect();
let mut description = Vec::new();
text::white_list_description(&items.join(&b", "[..]), &mut description);
String::from_utf8_lossy(&description).into_owned()
}
fn try_description(&self) -> Result<String, Error> {
for v in &self.list {
Input::Value(v).to_bytes()?;
}
Ok(self.description())
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
if value.is_array() {
return Ok(Verdict::INVALID);
}
if self.strict {
return Ok(Verdict::of(self.list.iter().any(|item| identical(value, Input::Value(item)))));
}
let value = value.to_bytes()?;
let value = strtolower(&value);
Ok(Verdict::of(self.list.iter().any(|item| matches!(item, Value::Str(s) if loose_str_eq(&value, s)))))
}
fn kind(&self) -> Type {
self.kind
}
}
#[derive(Debug, Clone)]
pub struct ArrayList<V> {
pub inner: V,
pub length: usize,
}
impl<V: Validator> ArrayList<V> {
pub fn new(inner: V, length: usize) -> Self {
Self { inner, length }
}
pub fn validator(&self) -> &V {
&self.inner
}
fn describe(&self, inner: &str) -> String {
let item = (!inner.is_empty() && inner != "0").then_some(inner.as_bytes());
let length = i64::try_from(self.length).unwrap_or(i64::MAX);
let mut description = Vec::new();
compose::array_list_description(length, item, &mut description);
String::from_utf8_lossy(&description).into_owned()
}
fn verdict(&self, valid: bool, inner: Option<Verdict>) -> Verdict {
match inner {
None => Verdict::of(valid),
Some(inner) => Verdict {
valid,
decided: inner.decided,
description: inner.into_description(&self.inner).map(|d| Cow::Owned(self.describe(&d))),
rule: None,
},
}
}
}
impl<V: Validator> Validator for ArrayList<V> {
fn description(&self) -> String {
self.describe(&self.inner.description())
}
fn try_description(&self) -> Result<String, Error> {
Ok(self.describe(&self.inner.try_description()?))
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
let View::Array(entries) = value.view() else {
return Ok(Verdict::INVALID);
};
let count = entries.len();
let mut decided: Option<Verdict> = None;
let mut last: Option<Verdict> = None;
for (_, element) in entries {
let v = self.inner.validate(element)?;
let valid = v.valid;
if v.decided {
decided = Some(v.clone());
}
last = Some(v);
if !valid {
break;
}
}
let valid = last.as_ref().is_none_or(|v| v.valid) && (self.length == 0 || count <= self.length);
Ok(self.verdict(valid, decided.or(last)))
}
fn is_array(&self) -> bool {
true
}
fn kind(&self) -> Type {
self.inner.kind()
}
}
#[derive(Debug, Clone, Copy)]
pub struct Assoc {
pub length: usize,
}
impl Default for Assoc {
fn default() -> Self {
Self { length: 65535 }
}
}
impl Validator for Assoc {
fn description(&self) -> String {
compose::ASSOC_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
if !value.is_array() {
return Ok(Verdict::INVALID);
}
let size = value.json_encode().map_or(0, |json| json.len());
if size > self.length {
return Ok(Verdict::INVALID);
}
let empty = matches!(value.view(), View::Array(e) if e.len() == 0);
Ok(Verdict::of(empty || !value.is_list()))
}
fn kind(&self) -> Type {
Type::Object
}
}
#[derive(Debug, Clone)]
pub struct Nullable<V>(
pub V,
);
impl<V: Validator> Nullable<V> {
pub fn validator(&self) -> &V {
&self.0
}
}
impl<V: Validator> Validator for Nullable<V> {
fn description(&self) -> String {
format!("{} or null", self.0.description())
}
fn try_description(&self) -> Result<String, Error> {
Ok(format!("{} or null", self.0.try_description()?))
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
if value.is_null() {
return Ok(Verdict::VALID);
}
let v = self.0.validate(value)?;
let (valid, decided, rule) = (v.valid, v.decided, v.rule);
let description = v.into_description(&self.0).map(|d| Cow::Owned(format!("{d} or null")));
Ok(Verdict { valid, description, decided, rule })
}
fn kind(&self) -> Type {
self.0.kind()
}
}