1use php_std::json::{self, Flags};
4use php_std::{ArrayKey, Extension, Str};
5
6use crate::enums::NullsPosition;
7use crate::query::Query;
8
9pub type Value = php_std::Value<Object>;
13
14pub type Array = php_std::Array<Object>;
16
17#[derive(Debug, Clone, PartialEq)]
19pub enum Object {
20 Query(Box<Query>),
24 Nulls(NullsPosition),
28 Row {
33 class: String,
35 fields: Array,
37 },
38}
39
40impl Extension for Object {
41 fn class(&self) -> &str {
43 match self {
44 Object::Query(_) => "Utopia\\Query\\Query",
45 Object::Nulls(_) => NullsPosition::PHP_CLASS,
46 Object::Row { class, .. } => class,
47 }
48 }
49
50 fn to_array(&self) -> Array {
53 match self {
54 Object::Row { fields, .. } => fields.clone(),
55 _ => Array::default(),
56 }
57 }
58}
59
60impl From<Query> for Value {
61 fn from(query: Query) -> Self {
63 Value::Ext(Object::Query(Box::new(query)))
64 }
65}
66
67impl From<NullsPosition> for Value {
68 fn from(nulls: NullsPosition) -> Self {
70 Value::Ext(Object::Nulls(nulls))
71 }
72}
73
74pub fn string(s: impl AsRef<[u8]>) -> Value {
76 Value::Str(Str::copy_from(s.as_ref()))
77}
78
79pub fn list<V: Into<Value>>(items: impl IntoIterator<Item = V>) -> Array {
81 Array::from_list(items.into_iter().map(Into::into).collect())
82}
83
84pub(crate) fn to_php_string(value: &Value) -> String {
87 match value.to_php_string() {
88 Ok(s) => String::from_utf8_lossy(s.as_bytes()).into_owned(),
89 Err(_) => String::new(),
90 }
91}
92
93pub(crate) fn json_encode(value: &Value, flags: Flags) -> Result<String, json::Error> {
96 json::encode(&enums_as_values(value), flags, json::DEFAULT_DEPTH)
97}
98
99fn enums_as_values(value: &Value) -> Value {
101 match value {
102 Value::Ext(Object::Nulls(n)) => Value::from(n.as_str()),
103 Value::Array(a) => Value::Array(map_array(a)),
104 Value::Object(a) => Value::Object(map_array(a)),
105 other => other.clone(),
106 }
107}
108
109fn map_array(a: &Array) -> Array {
110 let mut out = Array::with_capacity(a.len());
111 for (k, v) in a.iter() {
112 out.set(k.to_owned(), enums_as_values(v));
113 }
114 out
115}
116
117pub(crate) fn identical(a: &Value, b: &Value) -> bool {
120 match (a, b) {
121 (Value::Ext(Object::Nulls(x)), Value::Ext(Object::Nulls(y))) => x == y,
122 (Value::Array(x), Value::Array(y)) => {
123 x.len() == y.len() && x.iter().zip(y.iter()).all(|((ka, va), (kb, vb))| ka == kb && identical(va, vb))
124 }
125 _ => a.strict_eq(b),
126 }
127}
128
129pub trait IntoValue {
132 fn into_value(self) -> Value;
134}
135
136impl IntoValue for Value {
137 fn into_value(self) -> Value {
138 self
139 }
140}
141
142impl IntoValue for &Value {
143 fn into_value(self) -> Value {
144 self.clone()
145 }
146}
147
148macro_rules! into_value_int {
149 ($($t:ty),*) => {$(
150 impl IntoValue for $t {
151 fn into_value(self) -> Value {
152 Value::Int(self as i64)
153 }
154 }
155 )*};
156}
157
158into_value_int!(i8, i16, i32, i64, u8, u16, u32, isize);
159
160impl IntoValue for f64 {
161 fn into_value(self) -> Value {
162 Value::Float(self)
163 }
164}
165
166impl IntoValue for f32 {
167 fn into_value(self) -> Value {
168 Value::Float(self as f64)
169 }
170}
171
172impl IntoValue for bool {
173 fn into_value(self) -> Value {
174 Value::Bool(self)
175 }
176}
177
178impl IntoValue for &str {
179 fn into_value(self) -> Value {
180 string(self)
181 }
182}
183
184impl IntoValue for String {
185 fn into_value(self) -> Value {
186 Value::Str(Str::from(self))
187 }
188}
189
190impl IntoValue for &String {
191 fn into_value(self) -> Value {
192 string(self)
193 }
194}
195
196impl IntoValue for Str {
197 fn into_value(self) -> Value {
198 Value::Str(self)
199 }
200}
201
202impl IntoValue for Array {
203 fn into_value(self) -> Value {
204 Value::Array(self)
205 }
206}
207
208impl IntoValue for Query {
209 fn into_value(self) -> Value {
210 Value::from(self)
211 }
212}
213
214impl IntoValue for NullsPosition {
215 fn into_value(self) -> Value {
216 Value::from(self)
217 }
218}
219
220impl<T: IntoValue> IntoValue for Option<T> {
221 fn into_value(self) -> Value {
222 self.map(IntoValue::into_value).unwrap_or(Value::Null)
223 }
224}
225
226pub trait IntoValues {
229 fn into_values(self) -> Array;
231}
232
233impl IntoValues for Array {
234 fn into_values(self) -> Array {
235 self
236 }
237}
238
239impl<T: IntoValue, const N: usize> IntoValues for [T; N] {
240 fn into_values(self) -> Array {
241 Array::from_list(self.into_iter().map(IntoValue::into_value).collect())
242 }
243}
244
245impl<T: IntoValue> IntoValues for Vec<T> {
246 fn into_values(self) -> Array {
247 Array::from_list(self.into_iter().map(IntoValue::into_value).collect())
248 }
249}
250
251impl<T: IntoValue + Clone> IntoValues for &[T] {
252 fn into_values(self) -> Array {
253 Array::from_list(self.iter().cloned().map(IntoValue::into_value).collect())
254 }
255}
256
257pub(crate) fn concat(value: &Value) -> Result<std::borrow::Cow<'_, str>, crate::Error> {
260 use std::borrow::Cow;
261 match value {
262 Value::Str(s) => Ok(String::from_utf8_lossy(s.as_bytes())),
263 Value::Object(_) | Value::Ext(_) => Err(crate::Error::Engine(format!(
264 "Object of class {} could not be converted to string",
265 value.debug_type()
266 ))),
267 other => Ok(Cow::Owned(to_php_string(other))),
268 }
269}
270
271pub(crate) fn array_key(value: &Value) -> Result<ArrayKey, crate::Error> {
275 Ok(match value {
276 Value::Str(s) => ArrayKey::normalize(s.clone()),
277 Value::Int(i) => ArrayKey::Int(*i),
278 Value::Float(f) => ArrayKey::Int(php_std::format::dval_to_lval(*f)),
279 Value::Bool(b) => ArrayKey::Int(i64::from(*b)),
280 Value::Null => ArrayKey::Str(Str::EMPTY),
281 other => {
282 return Err(crate::Error::Type(format!("Cannot access offset of type {} on array", value_name(other))));
283 }
284 })
285}
286
287pub(crate) fn value_name(value: &Value) -> &str {
292 match value {
293 Value::Bool(true) => "true",
294 Value::Bool(false) => "false",
295 other => other.debug_type(),
296 }
297}
298
299pub(crate) fn concat_bytes(value: &Value) -> Result<std::borrow::Cow<'_, [u8]>, crate::Error> {
301 use std::borrow::Cow;
302 match value {
303 Value::Str(s) => Ok(Cow::Borrowed(s.as_bytes())),
304 other => Ok(Cow::Owned(concat(other)?.into_owned().into_bytes())),
305 }
306}
307
308const PHP_SOURCES: &str = "/usr/src/code/packages/query/src/";
311
312#[derive(Debug, Clone, Copy)]
324pub(crate) struct Param<'f> {
325 function: &'f str,
326 position: u8,
327 name: &'static str,
328 callee: Callee,
329}
330
331#[derive(Debug, Clone, Copy)]
332enum Callee {
333 Method { file: &'static str, line: u32 },
335 Closure,
338 Internal,
340}
341
342impl<'f> Param<'f> {
343 pub(crate) const fn method(
346 function: &'f str,
347 position: u8,
348 name: &'static str,
349 file: &'static str,
350 line: u32,
351 ) -> Self {
352 Param { function, position, name, callee: Callee::Method { file, line } }
353 }
354
355 pub(crate) const fn closure(function: &'f str, position: u8, name: &'static str) -> Self {
358 Param { function, position, name, callee: Callee::Closure }
359 }
360
361 pub(crate) const fn internal(function: &'f str, position: u8, name: &'static str) -> Self {
363 Param { function, position, name, callee: Callee::Internal }
364 }
365
366 pub(crate) fn string<'a>(&self, value: &'a Value) -> Result<std::borrow::Cow<'a, str>, crate::Error> {
368 use std::borrow::Cow;
369 Ok(match value {
370 Value::Str(s) => String::from_utf8_lossy(s.as_bytes()),
371 Value::Null if matches!(self.callee, Callee::Internal) => Cow::Borrowed(""),
372 Value::Int(_) | Value::Float(_) | Value::Bool(_) => Cow::Owned(to_php_string(value)),
373 other => return Err(self.type_error("string", other)),
374 })
375 }
376
377 pub(crate) fn bytes<'a>(&self, value: &'a Value) -> Result<std::borrow::Cow<'a, [u8]>, crate::Error> {
379 use std::borrow::Cow;
380 match value {
381 Value::Str(s) => Ok(Cow::Borrowed(s.as_bytes())),
382 other => Ok(Cow::Owned(self.string(other)?.into_owned().into_bytes())),
383 }
384 }
385
386 pub(crate) fn array<'a>(&self, value: &'a Value) -> Result<&'a Array, crate::Error> {
388 match value {
389 Value::Array(a) => Ok(a),
390 other => Err(self.type_error("array", other)),
391 }
392 }
393
394 pub(crate) fn type_error(&self, expected: &str, value: &Value) -> crate::Error {
396 let mut message = format!(
397 "{}(): Argument #{} (${}) must be of type {expected}, {} given",
398 self.function,
399 self.position,
400 self.name,
401 value_name(value)
402 );
403 if let Callee::Method { file, line } = self.callee {
404 message.push_str(&format!(", called in {PHP_SOURCES}{file} on line {line}"));
405 }
406 crate::Error::Type(message)
407 }
408}