use std::{error::Error as ErrorTrait, ffi::NulError, fmt::Display};
use crate::php::{
enums::DataType,
exceptions::PhpException,
flags::{ClassFlags, ZvalTypeFlags},
};
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Error {
IncorrectArguments(u32, u32),
ZvalConversion(DataType),
UnknownDatatype(u32),
InvalidTypeToDatatype(ZvalTypeFlags),
InvalidScope,
InvalidPointer,
InvalidProperty,
InvalidCString,
Callable,
InvalidException(ClassFlags),
IntegerOverflow,
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::IncorrectArguments(n, expected) => write!(
f,
"Expected at least {} arguments, got {} arguments.",
expected, n
),
Error::ZvalConversion(ty) => write!(
f,
"Could not convert Zval from type {} into primitive type.",
ty
),
Error::UnknownDatatype(dt) => write!(f, "Unknown datatype {}.", dt),
Error::InvalidTypeToDatatype(dt) => {
write!(f, "Type flags did not contain a datatype: {:?}", dt)
}
Error::InvalidScope => write!(f, "Invalid scope."),
Error::InvalidPointer => write!(f, "Invalid pointer."),
Error::InvalidProperty => write!(f, "Property does not exist on object."),
Error::InvalidCString => write!(
f,
"String given contains NUL-bytes which cannot be present in a C string."
),
Error::Callable => write!(f, "Could not call given function."),
Error::InvalidException(flags) => {
write!(f, "Invalid exception type was thrown: {:?}", flags)
}
Error::IntegerOverflow => {
write!(f, "Converting integer arguments resulted in an overflow.")
}
}
}
}
impl ErrorTrait for Error {}
impl From<NulError> for Error {
fn from(_: NulError) -> Self {
Self::InvalidCString
}
}
impl<'a> From<Error> for PhpException<'a> {
fn from(err: Error) -> Self {
Self::default(err.to_string())
}
}