use php_std::json::{self, Flags};
use php_std::{ArrayKey, Extension, Str};
use crate::enums::NullsPosition;
use crate::query::Query;
pub type Value = php_std::Value<Object>;
pub type Array = php_std::Array<Object>;
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
Query(Box<Query>),
Nulls(NullsPosition),
Row {
class: String,
fields: Array,
},
}
impl Extension for Object {
fn class(&self) -> &str {
match self {
Object::Query(_) => "Utopia\\Query\\Query",
Object::Nulls(_) => NullsPosition::PHP_CLASS,
Object::Row { class, .. } => class,
}
}
fn to_array(&self) -> Array {
match self {
Object::Row { fields, .. } => fields.clone(),
_ => Array::default(),
}
}
}
impl From<Query> for Value {
fn from(query: Query) -> Self {
Value::Ext(Object::Query(Box::new(query)))
}
}
impl From<NullsPosition> for Value {
fn from(nulls: NullsPosition) -> Self {
Value::Ext(Object::Nulls(nulls))
}
}
pub fn string(s: impl AsRef<[u8]>) -> Value {
Value::Str(Str::copy_from(s.as_ref()))
}
pub fn list<V: Into<Value>>(items: impl IntoIterator<Item = V>) -> Array {
Array::from_list(items.into_iter().map(Into::into).collect())
}
pub(crate) fn to_php_string(value: &Value) -> String {
match value.to_php_string() {
Ok(s) => String::from_utf8_lossy(s.as_bytes()).into_owned(),
Err(_) => String::new(),
}
}
pub(crate) fn json_encode(value: &Value, flags: Flags) -> Result<String, json::Error> {
json::encode(&enums_as_values(value), flags, json::DEFAULT_DEPTH)
}
fn enums_as_values(value: &Value) -> Value {
match value {
Value::Ext(Object::Nulls(n)) => Value::from(n.as_str()),
Value::Array(a) => Value::Array(map_array(a)),
Value::Object(a) => Value::Object(map_array(a)),
other => other.clone(),
}
}
fn map_array(a: &Array) -> Array {
let mut out = Array::with_capacity(a.len());
for (k, v) in a.iter() {
out.set(k.to_owned(), enums_as_values(v));
}
out
}
pub(crate) fn identical(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Ext(Object::Nulls(x)), Value::Ext(Object::Nulls(y))) => x == y,
(Value::Array(x), Value::Array(y)) => {
x.len() == y.len() && x.iter().zip(y.iter()).all(|((ka, va), (kb, vb))| ka == kb && identical(va, vb))
}
_ => a.strict_eq(b),
}
}
pub trait IntoValue {
fn into_value(self) -> Value;
}
impl IntoValue for Value {
fn into_value(self) -> Value {
self
}
}
impl IntoValue for &Value {
fn into_value(self) -> Value {
self.clone()
}
}
macro_rules! into_value_int {
($($t:ty),*) => {$(
impl IntoValue for $t {
fn into_value(self) -> Value {
Value::Int(self as i64)
}
}
)*};
}
into_value_int!(i8, i16, i32, i64, u8, u16, u32, isize);
impl IntoValue for f64 {
fn into_value(self) -> Value {
Value::Float(self)
}
}
impl IntoValue for f32 {
fn into_value(self) -> Value {
Value::Float(self as f64)
}
}
impl IntoValue for bool {
fn into_value(self) -> Value {
Value::Bool(self)
}
}
impl IntoValue for &str {
fn into_value(self) -> Value {
string(self)
}
}
impl IntoValue for String {
fn into_value(self) -> Value {
Value::Str(Str::from(self))
}
}
impl IntoValue for &String {
fn into_value(self) -> Value {
string(self)
}
}
impl IntoValue for Str {
fn into_value(self) -> Value {
Value::Str(self)
}
}
impl IntoValue for Array {
fn into_value(self) -> Value {
Value::Array(self)
}
}
impl IntoValue for Query {
fn into_value(self) -> Value {
Value::from(self)
}
}
impl IntoValue for NullsPosition {
fn into_value(self) -> Value {
Value::from(self)
}
}
impl<T: IntoValue> IntoValue for Option<T> {
fn into_value(self) -> Value {
self.map(IntoValue::into_value).unwrap_or(Value::Null)
}
}
pub trait IntoValues {
fn into_values(self) -> Array;
}
impl IntoValues for Array {
fn into_values(self) -> Array {
self
}
}
impl<T: IntoValue, const N: usize> IntoValues for [T; N] {
fn into_values(self) -> Array {
Array::from_list(self.into_iter().map(IntoValue::into_value).collect())
}
}
impl<T: IntoValue> IntoValues for Vec<T> {
fn into_values(self) -> Array {
Array::from_list(self.into_iter().map(IntoValue::into_value).collect())
}
}
impl<T: IntoValue + Clone> IntoValues for &[T] {
fn into_values(self) -> Array {
Array::from_list(self.iter().cloned().map(IntoValue::into_value).collect())
}
}
pub(crate) fn concat(value: &Value) -> Result<std::borrow::Cow<'_, str>, crate::Error> {
use std::borrow::Cow;
match value {
Value::Str(s) => Ok(String::from_utf8_lossy(s.as_bytes())),
Value::Object(_) | Value::Ext(_) => Err(crate::Error::Engine(format!(
"Object of class {} could not be converted to string",
value.debug_type()
))),
other => Ok(Cow::Owned(to_php_string(other))),
}
}
pub(crate) fn array_key(value: &Value) -> Result<ArrayKey, crate::Error> {
Ok(match value {
Value::Str(s) => ArrayKey::normalize(s.clone()),
Value::Int(i) => ArrayKey::Int(*i),
Value::Float(f) => ArrayKey::Int(php_std::format::dval_to_lval(*f)),
Value::Bool(b) => ArrayKey::Int(i64::from(*b)),
Value::Null => ArrayKey::Str(Str::EMPTY),
other => {
return Err(crate::Error::Type(format!("Cannot access offset of type {} on array", value_name(other))));
}
})
}
pub(crate) fn value_name(value: &Value) -> &str {
match value {
Value::Bool(true) => "true",
Value::Bool(false) => "false",
other => other.debug_type(),
}
}
pub(crate) fn concat_bytes(value: &Value) -> Result<std::borrow::Cow<'_, [u8]>, crate::Error> {
use std::borrow::Cow;
match value {
Value::Str(s) => Ok(Cow::Borrowed(s.as_bytes())),
other => Ok(Cow::Owned(concat(other)?.into_owned().into_bytes())),
}
}
const PHP_SOURCES: &str = "/usr/src/code/packages/query/src/";
#[derive(Debug, Clone, Copy)]
pub(crate) struct Param<'f> {
function: &'f str,
position: u8,
name: &'static str,
callee: Callee,
}
#[derive(Debug, Clone, Copy)]
enum Callee {
Method { file: &'static str, line: u32 },
Closure,
Internal,
}
impl<'f> Param<'f> {
pub(crate) const fn method(
function: &'f str,
position: u8,
name: &'static str,
file: &'static str,
line: u32,
) -> Self {
Param { function, position, name, callee: Callee::Method { file, line } }
}
pub(crate) const fn closure(function: &'f str, position: u8, name: &'static str) -> Self {
Param { function, position, name, callee: Callee::Closure }
}
pub(crate) const fn internal(function: &'f str, position: u8, name: &'static str) -> Self {
Param { function, position, name, callee: Callee::Internal }
}
pub(crate) fn string<'a>(&self, value: &'a Value) -> Result<std::borrow::Cow<'a, str>, crate::Error> {
use std::borrow::Cow;
Ok(match value {
Value::Str(s) => String::from_utf8_lossy(s.as_bytes()),
Value::Null if matches!(self.callee, Callee::Internal) => Cow::Borrowed(""),
Value::Int(_) | Value::Float(_) | Value::Bool(_) => Cow::Owned(to_php_string(value)),
other => return Err(self.type_error("string", other)),
})
}
pub(crate) fn bytes<'a>(&self, value: &'a Value) -> Result<std::borrow::Cow<'a, [u8]>, crate::Error> {
use std::borrow::Cow;
match value {
Value::Str(s) => Ok(Cow::Borrowed(s.as_bytes())),
other => Ok(Cow::Owned(self.string(other)?.into_owned().into_bytes())),
}
}
pub(crate) fn array<'a>(&self, value: &'a Value) -> Result<&'a Array, crate::Error> {
match value {
Value::Array(a) => Ok(a),
other => Err(self.type_error("array", other)),
}
}
pub(crate) fn type_error(&self, expected: &str, value: &Value) -> crate::Error {
let mut message = format!(
"{}(): Argument #{} (${}) must be of type {expected}, {} given",
self.function,
self.position,
self.name,
value_name(value)
);
if let Callee::Method { file, line } = self.callee {
message.push_str(&format!(", called in {PHP_SOURCES}{file} on line {line}"));
}
crate::Error::Type(message)
}
}