use php_std::encoding::{base64_decode, base64_encode};
use php_std::json::{self, Flags};
use php_std::{Array, ArrayKey, Value};
use crate::Error;
#[derive(Debug, Clone, PartialEq)]
pub struct Store {
data: Value,
key: Option<Vec<u8>>,
}
impl Default for Store {
fn default() -> Self {
Self { data: Value::Array(Array::new()), key: None }
}
}
impl Store {
pub fn new() -> Self {
Self::default()
}
pub fn property(&self, key: &[u8]) -> Option<&Value> {
self.properties().get(&ArrayKey::from_bytes(key)).filter(|v| !matches!(v, Value::Null))
}
pub fn set_property(&mut self, key: &[u8], value: Value) -> &mut Self {
self.properties_mut().set(ArrayKey::from_bytes(key), value);
self
}
pub fn properties(&self) -> &Array {
match &self.data {
Value::Array(data) => data,
_ => unreachable!("a store holds an array"),
}
}
fn properties_mut(&mut self) -> &mut Array {
match &mut self.data {
Value::Array(data) => data,
_ => unreachable!("a store holds an array"),
}
}
pub fn key(&self) -> Option<&[u8]> {
self.key.as_deref()
}
pub fn set_key(&mut self, key: Option<&[u8]>) -> &mut Self {
self.key = key.map(<[u8]>::to_vec);
self
}
pub fn encode(&self) -> Result<String, Error> {
let json = json::encode(&self.data, Flags::THROW_ON_ERROR, json::DEFAULT_DEPTH).map_err(Error::json)?;
Ok(base64_encode(json.as_bytes()))
}
pub fn decode(&mut self, data: &[u8]) -> &mut Self {
let Some(decoded) = base64_decode(data, true) else {
return self;
};
if let Ok(Value::Array(values)) = json::decode(&decoded, Some(true), json::DEFAULT_DEPTH, Flags::THROW_ON_ERROR)
{
let properties = self.properties_mut();
if properties.is_empty() && properties.next_index().is_none() {
*properties = values;
return self;
}
for (key, value) in values {
properties.set(key, value);
}
}
self
}
}