use php_std::url::parse_url;
use crate::object::{Error, Input, Type, Url, Validator, Verdict, is_valid_via_validate, network, text};
#[derive(Debug, Clone, Default)]
pub struct Hostname {
pub allow_list: Vec<String>,
}
impl Hostname {
pub fn new(allow_list: Vec<String>) -> Self {
Self { allow_list }
}
pub fn matches(&self, value: &str) -> bool {
self.matches_bytes(value.as_bytes())
}
fn matches_bytes(&self, value: &[u8]) -> bool {
allowed(&self.allow_list, value)
}
}
fn allowed(allow_list: &[String], value: &[u8]) -> bool {
if !network::hostname(value) {
return false;
}
allow_list.is_empty() || allow_list.iter().any(|allowed| network::hostname_allowed(value, allowed.as_bytes()))
}
impl Validator for Hostname {
fn description(&self) -> String {
network::HOSTNAME_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(value.as_str().is_some_and(|s| self.matches_bytes(s))))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Default)]
pub struct Host {
pub whitelist: Vec<String>,
}
impl Host {
pub fn new(whitelist: Vec<String>) -> Self {
Self { whitelist }
}
}
impl Validator for Host {
fn description(&self) -> String {
let mut description = Vec::new();
network::host_description(self.whitelist.join(", ").as_bytes(), &mut description);
String::from_utf8_lossy(&description).into_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
if !Url::default().validate(value)?.valid {
return Ok(Verdict::INVALID);
}
let url = value.to_bytes()?;
let host = parse_url(&url).and_then(|u| u.host());
Ok(Verdict::of(host.is_some_and(|h| allowed(&self.whitelist, &h))))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Label;
impl Label {
pub const MAX_LENGTH: usize = text::LABEL_MAX_LENGTH as usize;
}
impl Validator for Label {
fn description(&self) -> String {
text::LABEL_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(value.as_str().is_some_and(text::label)))
}
fn kind(&self) -> Type {
Type::String
}
}