use std::path::PathBuf;
use serde_json::Value;
use crate::{Deserializer, Functions, GetDot, Placeholder, JSON};
#[derive(Default, Clone)]
pub struct Context {
data: Value,
directory: Option<PathBuf>,
functions: Functions,
current: Value
}
impl Context {
pub fn new() -> Self {
Self::default()
}
pub fn with_data(mut self, data: Value) -> Self {
self.data = data.into();
self
}
pub fn set_data(&mut self, data: Value) -> &mut Self {
self.data = data.into();
self
}
pub fn data(&self) -> &Value {
&self.data
}
pub fn set_function(&mut self, name: impl AsRef<str>, function: impl Fn(&Deserializer, &Context, &Placeholder) -> serde_json::Result<Value> + 'static) -> &mut Self {
self.functions.register(name, function);
self
}
pub fn with_function(mut self, name: impl AsRef<str>, function: impl Fn(&Deserializer, &Context, &Placeholder) -> serde_json::Result<Value> + 'static) -> Self {
self.set_function(name, function);
self
}
pub fn functions(&self) -> &Functions {
&self.functions
}
pub fn with_override(mut self, new_value: Value) -> Self {
self.override_data(new_value);
self
}
pub fn override_data(&mut self, new_value: Value) -> &mut Self {
self.data.override_recursive(new_value);
self
}
pub fn with_additional_data(mut self, new_value: Value) -> Self {
self.add_data(new_value);
self
}
pub fn add_data(&mut self, new_value: Value) -> &mut Self {
self.data.add_recursive(new_value);
self
}
pub fn with_directory(mut self, directory: Option<PathBuf>) -> Self {
self.directory = directory;
self
}
pub fn set_directory(&mut self, directory: Option<PathBuf>) -> &mut Self {
self.directory = directory;
self
}
pub fn directory(&self) -> Option<&PathBuf> {
self.directory.as_ref()
}
pub(crate) fn set_current_data(&mut self, current: Value) {
self.current = current;
}
pub fn find(&self, deserializer: &Deserializer, placeholder: &Placeholder) -> serde_json::Result<Value> {
self
.data
.get_dot_deserializing(placeholder.path(), deserializer, self)
.or_else(|_| self.current.get_dot_deserializing(placeholder.path(), deserializer, self))
}
}