use php_std::types::KeyRef;
use php_std::{Array, Value};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Candidate {
state: Array,
}
impl Candidate {
pub fn new(state: Array) -> Self {
Candidate { state }
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.state.get_ref(KeyRef::normalize(key.as_bytes())).filter(|v| !matches!(v, Value::Null))
}
pub fn get_or<'a>(&'a self, key: &str, default: &'a Value) -> &'a Value {
self.get(key).unwrap_or(default)
}
pub fn set(&mut self, key: &str, value: Value) -> &mut Self {
self.state.set(KeyRef::normalize(key.as_bytes()).to_owned(), value);
self
}
pub fn remove(&mut self, key: &str) -> &mut Self {
self.state.remove(&KeyRef::normalize(key.as_bytes()).to_owned());
self
}
pub fn states(&self) -> &Array {
&self.state
}
}
impl<const N: usize> From<[(&str, Value); N]> for Candidate {
fn from(pairs: [(&str, Value); N]) -> Self {
let mut candidate = Candidate::default();
for (key, value) in pairs {
candidate.set(key, value);
}
candidate
}
}
impl From<Array> for Candidate {
fn from(state: Array) -> Self {
Candidate::new(state)
}
}