use php_std::format::Arg;
use php_std::{Array, ArrayKey, Str, Value};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Options(Array);
impl Options {
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, key: &str, value: impl OptionValue) {
self.0.set(ArrayKey::from_bytes(key.as_bytes()), value.into_value());
}
pub fn raw(&self, key: &str) -> Option<&Value> {
self.0.get(&ArrayKey::from_bytes(key.as_bytes()))
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.raw(key).filter(|v| !matches!(v, Value::Null))
}
pub fn as_array(&self) -> &Array {
&self.0
}
pub(crate) fn long_or(&self, key: &str, default: i64) -> i64 {
self.raw(key).map(to_long).unwrap_or(default)
}
pub(crate) fn string(&self, key: &str) -> Option<&[u8]> {
match self.raw(key) {
Some(Value::Str(s)) => Some(s),
_ => None,
}
}
pub(crate) fn int(&self, key: &str) -> Option<i64> {
match self.raw(key) {
Some(Value::Int(i)) => Some(*i),
_ => None,
}
}
}
pub trait OptionValue {
fn into_value(self) -> Value;
}
impl OptionValue for Value {
fn into_value(self) -> Value {
self
}
}
impl OptionValue for &str {
fn into_value(self) -> Value {
Value::Str(Str::copy_from(self.as_bytes()))
}
}
impl OptionValue for String {
fn into_value(self) -> Value {
Value::Str(Str::from(self.into_bytes()))
}
}
impl OptionValue for Vec<u8> {
fn into_value(self) -> Value {
Value::Str(Str::from(self))
}
}
impl OptionValue for i64 {
fn into_value(self) -> Value {
Value::Int(self)
}
}
impl OptionValue for i32 {
fn into_value(self) -> Value {
Value::Int(i64::from(self))
}
}
impl OptionValue for bool {
fn into_value(self) -> Value {
Value::Bool(self)
}
}
impl From<Array> for Options {
fn from(array: Array) -> Self {
Options(array)
}
}
pub(crate) fn to_long(value: &Value) -> i64 {
arg(value).to_int()
}
pub(crate) fn truthy(value: &Value) -> bool {
arg(value).to_bool()
}
pub(crate) fn arg(value: &Value) -> Arg<'_> {
match value {
Value::Null => Arg::Null,
Value::Bool(b) => Arg::Bool(*b),
Value::Int(i) => Arg::Int(*i),
Value::Float(f) => Arg::Float(*f),
Value::Str(s) => Arg::Str(s),
Value::Array(a) => Arg::Array(a.len()),
Value::Object(_) => Arg::Object,
Value::Ext(never) => match *never {},
}
}
pub(crate) fn type_name(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "bool",
Value::Int(_) => "int",
Value::Float(_) => "float",
Value::Str(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "stdClass",
Value::Ext(never) => match *never {},
}
}