use super::arguments::{Args, formatted};
use super::{dispatch, numbers, render_error, sprintf, upstream};
use crate::error::Result;
use crate::library::{CallLimits, data_depth_error};
use crate::value::{Value, ValueMap};
use laravel_rust_format_core::php::{
self, AsPhpValue, JsonFlags, PhpArray, PhpKey, PhpKeyRef, PhpKind, PhpValue,
};
use serde_json::Value as Json;
const UNBOUNDED: usize = usize::MAX;
pub(super) fn function<'a>(name: &str, args: Args<'_, 'a, '_>) -> Option<Result<Value<'a>>> {
if let Some(result) = numbers::php(name, args) {
return Some(result);
}
let view = |index| PhpView::bounded(args.value(index)?, args.limits.data_depth());
let result = dispatch!(name, args, {
"echo" => 1..=1, formatted(php::echo(view(0)?));
"boolval" => 1..=1, Ok(Value::Bool(php::boolval(&view(0)?)));
"intval" => 1..=1, Ok(Value::Int(php::intval(&view(0)?)));
"floatval" => 1..=1, Ok(Value::Float(php::floatval(&view(0)?)));
"strval" => 1..=1, formatted(php::strval(&view(0)?));
"loose_eq" => 2..=2, Ok(Value::Bool(php::loose_eq(&view(0)?, &view(1)?)));
"sprintf" | "sprintf_bytes" => 1..=UNBOUNDED, {
let parameters = (1..args.len()).map(view).collect::<Result<Vec<_>>>()?;
let mut limits = args.limits;
if name == "sprintf_bytes" {
limits.output = limits.output.min(limits.expansion);
}
let bytes = sprintf::bounded(args.str(0)?, ¶meters, limits)?;
if name == "sprintf_bytes" {
return Ok(Value::List(bytes.into_iter().map(|byte| Value::Int(byte.into())).collect()));
}
formatted(String::from_utf8(bytes).map_err(|_| render_error("PHP sprintf produced a non-UTF-8 byte string"))?)
};
"array_filter" => 1..=1, array_result(php::array_filter(&view(0)?));
"array_values" => 1..=1, array_result(php::array_values(&view(0)?));
"json_encode" => 1..=2, formatted(php::json_encode(&view(0)?, json_flags(args)?)
.map_err(|error| render_error(error.to_string()))?);
"ucfirst" => 1..=1, formatted(php::ucfirst(args.str(0)?));
"lcfirst" => 1..=1, formatted(php::lcfirst(args.str(0)?));
"ucwords" | "ucwords_with" => 1..=2, formatted(match args.opt_str(1)? {
Some(separators) => php::ucwords_with(args.str(0)?, separators),
None => php::ucwords(args.str(0)?),
});
"strtolower" => 1..=1, formatted(php::strtolower(args.str(0)?));
"strtoupper" => 1..=1, formatted(php::strtoupper(args.str(0)?));
});
result.or_else(|| super::php_strings::function(name, args))
}
pub(super) enum PhpView<'s> {
Scalar(PhpKind<'s>),
Array(Vec<(PhpKeyRef<'s>, Self)>),
}
impl<'s> PhpView<'s> {
pub(super) fn from_value(value: &'s Value<'_>) -> Result<Self> {
Self::bounded(value, CallLimits::default().data_depth())
}
pub(super) fn bounded(value: &'s Value<'_>, remaining: usize) -> Result<Self> {
let child_depth = || remaining.checked_sub(1).ok_or_else(data_depth_error);
Ok(match value {
Value::Null => Self::Scalar(PhpKind::Null),
Value::Int(value) => Self::Scalar(PhpKind::Int(*value)),
Value::Float(value) => Self::Scalar(PhpKind::Float(*value)),
Value::Bool(value) => Self::Scalar(PhpKind::Bool(*value)),
Value::Str(value) | Value::Html(value) => Self::Scalar(PhpKind::String(value)),
Value::List(values) => {
let remaining = child_depth()?;
Self::Array(
values
.iter()
.enumerate()
.map(|(index, value)| {
Ok((
PhpKeyRef::Int(index as i64),
Self::bounded(value, remaining)?,
))
})
.collect::<Result<_>>()?,
)
}
Value::Map(values) => {
let remaining = child_depth()?;
Self::Array(
values
.iter()
.map(|(key, value)| {
Ok((
PhpKeyRef::from_string(key),
Self::bounded(value, remaining)?,
))
})
.collect::<Result<_>>()?,
)
}
Value::Json(value) => Self::from_json(value, remaining)?,
Value::Object(object) => {
return Err(render_error(format!(
"PHP value helpers do not accept {} objects",
object.type_name()
)));
}
})
}
pub(super) fn into_owned(self) -> Result<PhpValue> {
Ok(match self {
Self::Scalar(PhpKind::Null) => PhpValue::Null,
Self::Scalar(PhpKind::Bool(value)) => PhpValue::Bool(value),
Self::Scalar(PhpKind::Int(value)) => PhpValue::Int(value),
Self::Scalar(PhpKind::Float(value)) => PhpValue::Float(value),
Self::Scalar(PhpKind::String(value)) => PhpValue::String(value.to_owned()),
Self::Array(entries) => {
let mut array = PhpArray::default();
for (key, value) in entries {
let key = match key {
PhpKeyRef::Int(key) => PhpKey::Int(key),
PhpKeyRef::String(key) => PhpKey::String(key.to_owned()),
};
array.insert(key, value.into_owned()?);
}
PhpValue::Array(array)
}
Self::Scalar(PhpKind::Array(_)) => return Err(render_error("invalid PHP array value")),
})
}
fn from_json(value: &'s Json, remaining: usize) -> Result<Self> {
let child_depth = || remaining.checked_sub(1).ok_or_else(data_depth_error);
Ok(match value {
Json::Null => Self::Scalar(PhpKind::Null),
Json::Bool(value) => Self::Scalar(PhpKind::Bool(*value)),
Json::Number(value) => Self::Scalar(match value.as_i64() {
Some(value) => PhpKind::Int(value),
None => PhpKind::Float(value.as_f64().unwrap_or(f64::NAN)),
}),
Json::String(value) => Self::Scalar(PhpKind::String(value)),
Json::Array(values) => {
let remaining = child_depth()?;
Self::Array(
values
.iter()
.enumerate()
.map(|(index, value)| {
Ok((
PhpKeyRef::Int(index as i64),
Self::from_json(value, remaining)?,
))
})
.collect::<Result<_>>()?,
)
}
Json::Object(values) => {
let remaining = child_depth()?;
Self::Array(
values
.iter()
.map(|(key, value)| {
Ok((
PhpKeyRef::from_string(key),
Self::from_json(value, remaining)?,
))
})
.collect::<Result<_>>()?,
)
}
})
}
}
impl AsPhpValue for PhpView<'_> {
type Element = Self;
fn kind(&self) -> PhpKind<'_> {
match self {
Self::Scalar(kind) => *kind,
Self::Array(entries) => PhpKind::Array(entries.len()),
}
}
fn entries(&self) -> impl Iterator<Item = (PhpKeyRef<'_>, &Self)> {
let entries = match self {
Self::Scalar(_) => &[][..],
Self::Array(entries) => entries.as_slice(),
};
entries.iter().map(|(key, value)| (*key, value))
}
}
fn array_result<'a>(result: laravel_rust_format_core::Result<PhpArray>) -> Result<Value<'a>> {
let array = upstream(result)?;
Ok(from_php(&array))
}
pub(super) fn from_php<'a>(value: &(impl AsPhpValue + ?Sized)) -> Value<'a> {
match value.kind() {
PhpKind::Null => Value::Null,
PhpKind::Bool(value) => Value::Bool(value),
PhpKind::Int(value) => Value::Int(value),
PhpKind::Float(value) => Value::Float(value),
PhpKind::String(value) => Value::string(value.to_owned()),
PhpKind::Array(_) => {
if value
.entries()
.enumerate()
.all(|(index, (key, _))| key == PhpKeyRef::Int(index as i64))
{
Value::List(value.entries().map(|(_, value)| from_php(value)).collect())
} else {
Value::Map(
value
.entries()
.map(|(key, value)| {
let key = match key {
PhpKeyRef::Int(key) => key.to_string(),
PhpKeyRef::String(key) => key.to_owned(),
};
(key, from_php(value))
})
.collect::<ValueMap<'a>>(),
)
}
}
}
}
fn json_flags(args: Args<'_, '_, '_>) -> Result<JsonFlags> {
let mut bits = args.int_or(1, 0)?;
let mut flags = JsonFlags::NONE;
for (bit, flag) in [
(1, JsonFlags::HEX_TAG),
(2, JsonFlags::HEX_AMP),
(4, JsonFlags::HEX_APOS),
(8, JsonFlags::HEX_QUOT),
(64, JsonFlags::UNESCAPED_SLASHES),
(128, JsonFlags::PRETTY_PRINT),
(256, JsonFlags::UNESCAPED_UNICODE),
(1024, JsonFlags::PRESERVE_ZERO_FRACTION),
] {
if bits & bit != 0 {
bits &= !bit;
flags |= flag;
}
}
if bits != 0 {
return Err(args.invalid(1, "supported PHP JSON flags"));
}
Ok(flags)
}