pub(crate) mod translations;
pub use crate::value::{Arg, Callable};
use crate::{
encode::{EncodeError, EncodingLimits, JsonFlags, e, encode_js, encode_json},
error::{Error, ErrorKind, Result},
value::{Value, expansion_error},
};
#[derive(Clone, Copy)]
pub(crate) struct CallLimits {
pub(crate) output: usize,
pub(crate) expansion: usize,
pub(crate) depth: usize,
}
impl Default for CallLimits {
fn default() -> Self {
Self {
output: 8 * 1024 * 1024,
expansion: 100_000,
depth: 64,
}
}
}
impl CallLimits {
pub(crate) fn check_bytes(self, bytes: Option<usize>) -> Result<()> {
if bytes.is_none_or(|bytes| bytes > self.output) {
return Err(Error::new(
ErrorKind::Limit,
"render output limit exceeded while evaluating text",
None,
));
}
Ok(())
}
pub(crate) fn charge_entries(&mut self, entries: usize) -> Result<()> {
self.expansion = self
.expansion
.checked_sub(entries)
.ok_or_else(expansion_error)?;
Ok(())
}
pub(crate) fn data_depth(self) -> usize {
self.depth.min(64)
}
}
pub(crate) fn data_depth_error() -> Error {
Error::new(
ErrorKind::Limit,
"collection data depth limit exceeded",
None,
)
}
pub(crate) fn fault(message: impl Into<String>) -> Error {
Error::new(ErrorKind::Render, message, None)
}
pub(crate) fn boolean(value: &Value<'_>) -> Result<bool> {
match value.scalar() {
Value::Bool(value) => Ok(value),
_ => Err(fault(format!("expected bool, got {}", value.type_name()))),
}
}
pub(crate) fn integer(value: &Value<'_>) -> Result<i64> {
match value.scalar() {
Value::Int(value) => Ok(value),
_ => Err(fault(format!(
"expected integer, got {}",
value.type_name()
))),
}
}
pub(crate) fn string<'b>(value: &'b Value<'_>) -> Result<&'b str> {
value
.as_str()
.ok_or_else(|| fault(format!("expected string, got {}", value.type_name())))
}
pub(crate) fn key(value: &Value<'_>) -> Result<String> {
match value.scalar() {
Value::Int(value) => Ok(value.to_string()),
Value::Str(value) => Ok(value.into_owned()),
_ => Err(fault("a map key must be a string or integer")),
}
}
pub(crate) fn blank(value: &Value<'_>) -> bool {
match value {
Value::Null | Value::Json(serde_json::Value::Null) => true,
Value::Str(text) => text.trim_matches(php_space).is_empty(),
Value::Json(serde_json::Value::String(text)) => text.trim_matches(php_space).is_empty(),
Value::List(items) => items.is_empty(),
Value::Map(items) => items.is_empty(),
Value::Json(serde_json::Value::Array(items)) => items.is_empty(),
Value::Json(serde_json::Value::Object(items)) => items.is_empty(),
_ => false,
}
}
pub(crate) fn php_space(ch: char) -> bool {
matches!(ch, ' ' | '\t' | '\r' | '\n' | '\0' | '\x0b')
}
pub(crate) fn encode(
name: &str,
values: &[Value<'_>],
limits: CallLimits,
) -> Result<(String, usize)> {
let [value, rest @ ..] = values else {
return Err(fault("encoding requires a value"));
};
if rest.len() > 2 {
return Err(fault("encoding accepts a value, flags and depth"));
}
let flags = rest
.first()
.map(|value| {
let entries = value.entries(limits.expansion.min(32))?;
let names = entries
.iter()
.map(|(_, value)| string(value))
.collect::<Result<Vec<_>>>()?;
JsonFlags::from_names(names).map_err(|_| fault("unknown JSON flag"))
})
.transpose()?;
let depth = rest
.get(1)
.map(|value| i32::try_from(integer(value)?).map_err(|_| fault("invalid JSON depth")))
.transpose()?;
let limits = EncodingLimits {
output: limits.output,
expansion: limits.expansion,
};
let encoded = if name == "js" {
encode_js(value, flags.unwrap_or_default(), depth, limits)
} else {
encode_json(value, flags, depth, limits)
};
match encoded {
Ok(encoded) => Ok(encoded),
Err(error @ (EncodeError::OutputLimit | EncodeError::ExpansionLimit)) => {
Err(Error::new(ErrorKind::Limit, error.to_string(), None))
}
Err(error)
if name == "js"
|| flags.is_some_and(|flags| flags.contains(JsonFlags::THROW_ON_ERROR)) =>
{
Err(fault(error.to_string()))
}
Err(_) => Ok((String::new(), 0)),
}
}
fn one<'a>(args: Vec<Arg<'a, '_>>) -> Result<Value<'a>> {
if args.len() == 1
&& let Some(Arg::Value(value)) = args.into_iter().next()
{
return Ok(value);
}
Err(fault("expected one value argument"))
}
fn reborrow<'a, 'c>(args: &'c mut [Arg<'a, '_>]) -> Vec<Arg<'a, 'c>> {
args.iter_mut()
.map(|arg| match arg {
Arg::Value(value) => Arg::Value(value.clone()),
Arg::Closure(closure) => Arg::Closure(&mut **closure),
})
.collect()
}
pub fn has_php_function(path: &str) -> bool {
path.starts_with("php::") && function(path, Vec::new()).is_some()
}
pub fn function<'a>(path: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
function_with_limits(path, args, CallLimits::default())
}
pub(crate) fn function_with_limits<'a>(
path: &str,
args: Vec<Arg<'a, '_>>,
limits: CallLimits,
) -> Option<Result<Value<'a>>> {
dispatch_function(path, args, limits, None)
}
pub(crate) fn function_with_clock_and_limits<'a>(
path: &str,
args: Vec<Arg<'a, '_>>,
clock: &dyn Fn() -> jiff::ZonedDateTime,
limits: CallLimits,
) -> Option<Result<Value<'a>>> {
dispatch_function(path, args, limits, Some(clock))
}
fn dispatch_function<'a>(
path: &str,
args: Vec<Arg<'a, '_>>,
limits: CallLimits,
clock: Option<&dyn Fn() -> jiff::ZonedDateTime>,
) -> Option<Result<Value<'a>>> {
let path = if path == "sprintf" {
"php::sprintf"
} else {
path
};
if path == "php::array_filter" && args.len() == 2 {
return Some(filter_php(args));
}
if let Some(result) = builtin_function(path, &args, limits) {
return Some(result);
}
let mut args = args;
if let Some(result) =
crate::collections::function_with_limits(path, reborrow(&mut args), limits)
{
return Some(result);
}
crate::formatting::call(path, args, clock, limits)
}
fn builtin_function<'a>(
path: &str,
args: &[Arg<'a, '_>],
limits: CallLimits,
) -> Option<Result<Value<'a>>> {
Some(match path {
"blank" | "filled" | "isset" | "empty" | "e" | "Some" => {
let [Arg::Value(value)] = args else {
return Some(Err(fault("expected one value argument")));
};
match path {
"blank" | "empty" => Ok(Value::Bool(blank(value))),
"filled" => Ok(Value::Bool(!blank(value))),
"isset" => Ok(Value::Bool(!value.is_null())),
"Some" => Ok(value.clone()),
_ => value.display().map(|text| {
Value::html(if value.is_trusted_html() {
text
} else {
e(&text)
})
}),
}
}
"nl2br" => {
let [Arg::Value(value)] = args else {
return Some(Err(fault("nl2br expects one value argument")));
};
safe_nl2br(value)
}
"json" | "js" => values(args)
.and_then(|values| encode(path, &values, limits))
.map(|(text, _)| Value::html(text)),
_ => return None,
})
}
fn values<'a>(args: &[Arg<'a, '_>]) -> Result<Vec<Value<'a>>> {
args.iter()
.map(|arg| match arg {
Arg::Value(value) => Ok(value.clone()),
Arg::Closure(_) => Err(fault("expected a value argument")),
})
.collect()
}
pub fn method<'a>(
name: &str,
receiver: &Value<'a>,
args: Vec<Arg<'a, '_>>,
) -> Option<Result<Value<'a>>> {
method_with_limits(name, receiver, args, CallLimits::default())
}
pub(crate) fn method_with_limits<'a>(
name: &str,
receiver: &Value<'a>,
args: Vec<Arg<'a, '_>>,
limits: CallLimits,
) -> Option<Result<Value<'a>>> {
if let Value::Object(object) = receiver {
let mut args = args;
if let Some(result) = object.method(name, reborrow(&mut args)) {
return Some(result);
}
return native_method(name, receiver, args, limits);
}
native_method(name, receiver, args, limits)
}
fn native_method<'a>(
name: &str,
receiver: &Value<'a>,
args: Vec<Arg<'a, '_>>,
limits: CallLimits,
) -> Option<Result<Value<'a>>> {
match name {
"is_some" | "is_none" | "to_string" if args.is_empty() => {
return Some(match name {
"to_string" => receiver.display().map(Value::string),
_ => Ok(Value::Bool(receiver.is_null() == (name == "is_none"))),
});
}
"unwrap_or" => {
return Some(one(args).map(|default| {
if receiver.is_null() {
default
} else {
receiver.clone()
}
}));
}
_ => {}
}
if let Some(text) = receiver.as_str()
&& let Some(result) = string_method(name, text, &args)
{
return Some(result);
}
if matches!(receiver.type_name(), "i64" | "f64")
&& let Some(result) = number_method(name, receiver, &args)
{
return Some(result);
}
if matches!(receiver.type_name(), "list" | "map")
&& let Some(result) = container_method(name, receiver, &args)
{
return Some(result);
}
let mut args = args;
if let Some(result) =
crate::collections::method_with_limits(name, receiver, reborrow(&mut args), limits)
{
return Some(result);
}
crate::formatting::method_with_limits(name, receiver, args, limits)
}
fn string_method<'a>(name: &str, text: &str, args: &[Arg<'a, '_>]) -> Option<Result<Value<'a>>> {
Some(match (name, args) {
("len", []) => Ok(Value::Int(text.len() as i64)),
("is_empty", []) => Ok(Value::Bool(text.is_empty())),
("is_not_empty", []) => Ok(Value::Bool(!text.is_empty())),
("to_lowercase", []) => Ok(Value::string(text.to_lowercase())),
("to_uppercase", []) => Ok(Value::string(text.to_uppercase())),
("to_ascii_uppercase", []) => Ok(Value::string(text.to_ascii_uppercase())),
("to_ascii_lowercase", []) => Ok(Value::string(text.to_ascii_lowercase())),
("trim", []) => Ok(Value::string(text.trim().to_owned())),
("trim_start", []) => Ok(Value::string(text.trim_start().to_owned())),
("trim_end", []) => Ok(Value::string(text.trim_end().to_owned())),
(
"starts_with" | "ends_with" | "contains" | "split" | "split_once" | "cmp",
[Arg::Value(value)],
) => string(value).and_then(|operand| {
Ok(match name {
"starts_with" => Value::Bool(text.starts_with(operand)),
"ends_with" => Value::Bool(text.ends_with(operand)),
"contains" => Value::Bool(text.contains(operand)),
"cmp" => Value::Int(text.cmp(operand) as i64),
"split_once" => text
.split_once(operand)
.map_or(Value::Null, |(left, right)| {
Value::List(vec![
Value::string(left.to_owned()),
Value::string(right.to_owned()),
])
}),
_ => {
let pieces = text
.split(operand)
.take(100_001)
.map(|item| Value::string(item.to_owned()))
.collect::<Vec<_>>();
if pieces.len() > 100_000 {
return Err(expansion_error());
}
Value::List(pieces)
}
})
}),
("replace", [Arg::Value(from), Arg::Value(to)]) => {
string(from).and_then(|from| string(to).map(|to| Value::string(text.replace(from, to))))
}
_ => return None,
})
}
fn number_method<'a>(
name: &str,
receiver: &Value<'a>,
args: &[Arg<'a, '_>],
) -> Option<Result<Value<'a>>> {
if !matches!(
name,
"abs" | "floor" | "ceil" | "round" | "min" | "max" | "clamp" | "pow" | "cmp"
) {
return None;
}
if name == "round" && !args.is_empty() {
return None;
}
Some((|| {
let arguments = values(args)?;
let overflow = || fault("integer overflow");
let bad = || fault(format!("invalid arguments for {name}"));
Ok(match (receiver.scalar(), arguments.as_slice()) {
(Value::Int(n), []) => match name {
"abs" => Value::Int(n.checked_abs().ok_or_else(overflow)?),
"floor" | "ceil" | "round" => Value::Int(n),
_ => return Err(bad()),
},
(Value::Int(n), [other]) => {
let other = integer(other)?;
Value::Int(match name {
"min" => n.min(other),
"max" => n.max(other),
"cmp" => n.cmp(&other) as i64,
"pow" => n
.checked_pow(u32::try_from(other).map_err(|_| bad())?)
.ok_or_else(overflow)?,
_ => return Err(bad()),
})
}
(Value::Int(n), [min, max]) if name == "clamp" => {
let (min, max) = (integer(min)?, integer(max)?);
if min > max {
return Err(bad());
}
Value::Int(n.clamp(min, max))
}
(Value::Float(n), []) => Value::Float(match name {
"abs" => n.abs(),
"floor" => n.floor(),
"ceil" => n.ceil(),
"round" => n.round(),
_ => return Err(bad()),
}),
(Value::Float(n), [other]) => {
if let Value::Float(other) = other.scalar() {
match name {
"min" => Value::Float(n.min(other)),
"max" => Value::Float(n.max(other)),
"pow" => Value::Float(n.powf(other)),
"cmp" => Value::Int(n.partial_cmp(&other).ok_or_else(bad)? as i64),
_ => return Err(bad()),
}
} else if name == "pow" {
Value::Float(n.powi(i32::try_from(integer(other)?).map_err(|_| bad())?))
} else {
return Err(bad());
}
}
(Value::Float(n), [min, max]) if name == "clamp" => {
let (Value::Float(min), Value::Float(max)) = (min.scalar(), max.scalar()) else {
return Err(bad());
};
if min.is_nan() || max.is_nan() || min > max {
return Err(bad());
}
Value::Float(n.clamp(min, max))
}
_ => return Err(bad()),
})
})())
}
fn container_method<'a>(
name: &str,
receiver: &Value<'a>,
args: &[Arg<'a, '_>],
) -> Option<Result<Value<'a>>> {
let len = match receiver {
Value::List(values) => values.len(),
Value::Map(values) => values.len(),
Value::Json(serde_json::Value::Array(values)) => values.len(),
Value::Json(serde_json::Value::Object(values)) => values.len(),
_ => return None,
};
Some(match (name, args) {
("len", []) => Ok(Value::Int(len as i64)),
("is_empty", []) => Ok(Value::Bool(len == 0)),
("is_not_empty", []) => Ok(Value::Bool(len != 0)),
("get" | "contains_key", [Arg::Value(value)]) => crate::eval::lookup_index(receiver, value)
.map(|entry| {
if name == "get" {
entry.unwrap_or(Value::Null)
} else {
Value::Bool(entry.is_some())
}
}),
_ => return None,
})
}
fn safe_nl2br<'a>(value: &Value<'_>) -> Result<Value<'a>> {
let escaped = e(string(value)?);
crate::formatting::function("php::nl2br", vec![Arg::Value(Value::string(escaped))])
.ok_or_else(|| fault("nl2br is unavailable"))?
.and_then(|output| output.display().map(Value::html))
}
fn filter_php<'a>(mut args: Vec<Arg<'a, '_>>) -> Result<Value<'a>> {
let [Arg::Value(input), Arg::Closure(callback)] = args.as_mut_slice() else {
return Err(fault("php::array_filter expects a collection and closure"));
};
let mut kept = Vec::new();
for (field, value) in input.entries(100_000)? {
let condition = callback.call(std::slice::from_ref(&value))?;
let truthy = crate::formatting::function("php::boolval", vec![Arg::Value(condition)])
.ok_or_else(|| fault("php::boolval is unavailable"))??;
if boolean(&truthy)? {
kept.push((field, value));
}
}
if kept.iter().enumerate().all(|(index, (field, _))| {
matches!(field.scalar(), Value::Int(field) if usize::try_from(field) == Ok(index))
}) {
Ok(Value::List(kept.into_iter().map(|(_, value)| value).collect()))
} else {
Ok(Value::Map(kept.into_iter().map(|(field, value)| Ok((key(&field)?, value))).collect::<Result<_>>()?))
}
}