use std::borrow::Cow;
use php_std::Value;
use php_std::filter::{FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_URL};
use php_std::json::{self as php_json, DEFAULT_DEPTH, Flags};
use php_std::url::parse_url;
use crate::compose::{
FCM_DESCRIPTION, FCM_EMAIL_ERROR, FCM_KEY_ERROR, FCM_OPTIONAL, FCM_REQUIRED, FCM_TYPE_ERROR, FCM_URL,
JSON_DESCRIPTION, fcm_optional_error, fcm_required_error, fcm_url_error, https_scheme, json_array_description,
json_length, json_object_description, non_empty, pem_private_key,
};
use crate::object::input::{View, filter_str};
use crate::object::{Error, Input, Type, Validator, Verdict, is_valid_via_validate};
fn decode(json: &[u8]) -> Option<Value> {
php_json::decode(json, None, DEFAULT_DEPTH, Flags::NONE).ok()
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Json;
impl Validator for Json {
fn description(&self) -> String {
JSON_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(match value.view() {
View::Array(_) => true,
View::Str(s) => decode(s).is_some(),
_ => false,
}))
}
fn kind(&self) -> Type {
Type::Object
}
}
fn fits(length: usize, encoded: Option<&[u8]>) -> bool {
json_length(php_length(length), encoded)
}
fn php_length(length: usize) -> i64 {
i64::try_from(length).unwrap_or(i64::MAX)
}
fn utf8(describe: impl FnOnce(&mut Vec<u8>)) -> String {
let mut description = Vec::new();
describe(&mut description);
String::from_utf8_lossy(&description).into_owned()
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Array {
pub length: usize,
}
impl Validator for Array {
fn description(&self) -> String {
utf8(|out| json_array_description(php_length(self.length), out))
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(match value.view() {
View::Str(s) => fits(self.length, Some(s)) && matches!(decode(s), Some(Value::Array(_))),
View::Array(e) => {
(e.len() == 0 || value.is_list())
&& fits(self.length, value.json_encode().as_deref().map(str::as_bytes))
}
_ => false,
}))
}
fn is_array(&self) -> bool {
true
}
fn kind(&self) -> Type {
Type::Array
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Object {
pub length: usize,
}
impl Validator for Object {
fn description(&self) -> String {
utf8(|out| json_object_description(php_length(self.length), out))
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(match value.view() {
View::Str(s) => fits(self.length, Some(s)) && matches!(decode(s), Some(Value::Object(_))),
View::Object(_) => fits(self.length, value.json_encode().as_deref().map(str::as_bytes)),
View::Array(e) => {
(e.len() == 0 || !value.is_list())
&& fits(self.length, value.json_encode().as_deref().map(str::as_bytes))
}
_ => false,
}))
}
fn kind(&self) -> Type {
Type::Object
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Fcm;
fn non_empty_string(value: Option<Input<'_>>) -> Option<&[u8]> {
value.and_then(Input::as_str).filter(|s| non_empty(s))
}
fn https_url(url: &[u8]) -> bool {
filter_str(url, FILTER_VALIDATE_URL, 0) && parse_url(url).and_then(|u| u.scheme()).is_some_and(|s| https_scheme(&s))
}
impl Fcm {
fn check(value: Input<'_>) -> Option<Result<(), Cow<'static, str>>> {
let credentials = value.is_object() || (value.is_array() && (is_empty(value) || !value.is_list()));
if !credentials {
return None;
}
for (field, purpose) in FCM_REQUIRED {
if non_empty_string(value.get(field)).is_none() {
return Some(Err(Cow::Owned(fcm_required_error(field, purpose))));
}
}
for field in FCM_OPTIONAL {
if let Some(v) = value.get(field)
&& non_empty_string(Some(v)).is_none()
{
return Some(Err(Cow::Owned(fcm_optional_error(field))));
}
}
let field = |name| non_empty_string(value.get(name)).unwrap_or_default();
if field("type") != b"service_account" {
return Some(Err(Cow::Borrowed(FCM_TYPE_ERROR)));
}
if !filter_str(field("client_email"), FILTER_VALIDATE_EMAIL, 0) {
return Some(Err(Cow::Borrowed(FCM_EMAIL_ERROR)));
}
if !pem_private_key(field("private_key")) {
return Some(Err(Cow::Borrowed(FCM_KEY_ERROR)));
}
for name in FCM_URL {
if value.get(name).is_some_and(|v| !v.is_null()) && !https_url(field(name)) {
return Some(Err(Cow::Owned(fcm_url_error(name))));
}
}
Some(Ok(()))
}
}
fn is_empty(value: Input<'_>) -> bool {
matches!(value.view(), View::Array(e) if e.len() == 0)
}
impl Validator for Fcm {
fn description(&self) -> String {
FCM_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
let decoded;
let value = match value.as_str() {
Some(json) => match decode(json) {
Some(z) => {
decoded = z;
Input::Value(&decoded)
}
None => return Ok(Verdict::decided(false, None)),
},
None => value,
};
Ok(match Self::check(value) {
None => Verdict::decided(false, None),
Some(Ok(())) => Verdict::decided(true, None),
Some(Err(error)) => Verdict::decided(false, Some(error)),
})
}
fn kind(&self) -> Type {
Type::Object
}
}