1use crate::{
4 boxed::ZBox,
5 error::{Error, Result},
6 exception::PhpException,
7 flags::DataType,
8 types::{ZendObject, Zval},
9};
10
11#[diagnostic::on_unimplemented(
14 message = "`{Self}` cannot be extracted from a PHP value",
15 label = "no `FromZval` implementation for `{Self}`"
16)]
17pub trait FromZval<'a>: Sized {
18 const TYPE: DataType;
20
21 const NULLABLE: bool = false;
26
27 fn from_zval(zval: &'a Zval) -> Option<Self>;
34
35 #[must_use]
41 fn from_missing() -> Option<Self> {
42 None
43 }
44
45 fn try_from_zval(zval: &'a Zval) -> Result<Self> {
55 Self::from_zval(zval).ok_or_else(|| Error::ZvalConversion(zval.get_type()))
56 }
57}
58
59impl<'a, T> FromZval<'a> for Option<T>
60where
61 T: FromZval<'a>,
62{
63 const TYPE: DataType = T::TYPE;
64 const NULLABLE: bool = true;
65
66 fn from_zval(zval: &'a Zval) -> Option<Self> {
67 T::from_zval(zval)
68 .map(Some)
69 .or_else(|| zval.dereference().is_null().then_some(None))
70 }
71
72 fn from_missing() -> Option<Self> {
73 Some(None)
74 }
75
76 fn try_from_zval(zval: &'a Zval) -> Result<Self> {
77 match T::try_from_zval(zval) {
78 Ok(value) => Ok(Some(value)),
79 Err(_) if zval.dereference().is_null() => Ok(None),
80 Err(err) => Err(err),
81 }
82 }
83}
84
85#[diagnostic::on_unimplemented(
91 message = "`{Self}` cannot be used as a PHP function argument",
92 label = "no `FromZval` or `FromZvalMut` implementation for `{Self}`",
93 note = "a variadic `#[php_class]` parameter is `&[ClassRef<T>]` or `&[ClassRefMut<T>]`",
94 note = "a variadic parameter must be spelled `&[T]` in the signature, a type alias hiding the slice is not detected"
95)]
96pub trait FromZvalMut<'a>: Sized {
97 const TYPE: DataType;
99
100 const NULLABLE: bool = false;
102
103 const BY_REF: bool = false;
107
108 fn from_zval_mut(zval: &'a mut Zval) -> Option<Self>;
115
116 #[must_use]
122 fn from_missing() -> Option<Self> {
123 None
124 }
125
126 fn try_from_zval_mut(zval: &'a mut Zval) -> Result<Self> {
136 let r#type = zval.get_type();
137 Self::from_zval_mut(zval).ok_or(Error::ZvalConversion(r#type))
138 }
139}
140
141impl<'a, T> FromZvalMut<'a> for T
142where
143 T: FromZval<'a>,
144{
145 const TYPE: DataType = <T as FromZval>::TYPE;
146 const NULLABLE: bool = <T as FromZval>::NULLABLE;
147
148 #[inline]
149 fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> {
150 Self::from_zval(zval)
151 }
152
153 #[inline]
154 fn from_missing() -> Option<Self> {
155 <T as FromZval>::from_missing()
156 }
157
158 #[inline]
159 fn try_from_zval_mut(zval: &'a mut Zval) -> Result<Self> {
160 Self::try_from_zval(zval)
161 }
162}
163
164pub trait FromZendObject<'a>: Sized {
178 fn from_zend_object(obj: &'a ZendObject) -> Result<Self>;
190}
191
192pub trait FromZendObjectMut<'a>: Sized {
198 fn from_zend_object_mut(obj: &'a mut ZendObject) -> Result<Self>;
210}
211
212impl<'a, T> FromZendObjectMut<'a> for T
213where
214 T: FromZendObject<'a>,
215{
216 #[inline]
217 fn from_zend_object_mut(obj: &'a mut ZendObject) -> Result<Self> {
218 Self::from_zend_object(obj)
219 }
220}
221
222pub trait IntoZendObject {
225 fn into_zend_object(self) -> Result<ZBox<ZendObject>>;
237}
238
239pub trait IntoZval: Sized {
246 const TYPE: DataType;
248
249 const NULLABLE: bool;
251
252 fn into_zval(self, persistent: bool) -> Result<Zval> {
273 let mut zval = Zval::new();
274 self.set_zval(&mut zval, persistent)?;
275 Ok(zval)
276 }
277
278 fn set_zval(self, zv: &mut Zval, persistent: bool) -> Result<()>;
300}
301
302impl IntoZval for () {
303 const TYPE: DataType = DataType::Void;
304 const NULLABLE: bool = true;
305
306 #[inline]
307 fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> {
308 zv.set_null();
309 Ok(())
310 }
311}
312
313impl<T> IntoZval for Option<T>
314where
315 T: IntoZval,
316{
317 const TYPE: DataType = T::TYPE;
318 const NULLABLE: bool = true;
319
320 #[inline]
321 fn set_zval(self, zv: &mut Zval, persistent: bool) -> Result<()> {
322 if let Some(val) = self {
323 val.set_zval(zv, persistent)
324 } else {
325 zv.set_null();
326 Ok(())
327 }
328 }
329}
330
331impl<T, E> IntoZval for std::result::Result<T, E>
332where
333 T: IntoZval,
334 E: Into<PhpException>,
335{
336 const TYPE: DataType = T::TYPE;
337 const NULLABLE: bool = T::NULLABLE;
338
339 fn set_zval(self, zv: &mut Zval, persistent: bool) -> Result<()> {
340 match self {
341 Ok(val) => val.set_zval(zv, persistent),
342 Err(e) => {
343 let ex: PhpException = e.into();
344 ex.throw();
345 Err(Error::pending_exception().unwrap_or(Error::Callable))
346 }
347 }
348 }
349}
350
351pub trait IntoZvalDyn {
357 fn as_zval(&self, persistent: bool) -> Result<Zval>;
372
373 fn get_type(&self) -> DataType;
375
376 fn stub_value(&self) -> String {
381 match self.as_zval(false) {
383 Ok(zval) => zval_to_stub(&zval),
384 Err(_) => "null".to_string(),
385 }
386 }
387}
388
389#[must_use]
391#[allow(clippy::match_same_arms)]
392pub fn zval_to_stub(zval: &Zval) -> String {
393 use crate::flags::DataType;
394
395 match zval.get_type() {
396 DataType::Null | DataType::Undef => "null".to_string(),
397 DataType::True => "true".to_string(),
398 DataType::False => "false".to_string(),
399 DataType::Long => zval
400 .long()
401 .map_or_else(|| "null".to_string(), |v| v.to_string()),
402 DataType::Double => zval
403 .double()
404 .map_or_else(|| "null".to_string(), |v| v.to_string()),
405 DataType::String => {
406 if let Some(s) = zval.str() {
407 let escaped = s
408 .replace('\\', "\\\\")
409 .replace('\'', "\\'")
410 .replace('\n', "\\n")
411 .replace('\r', "\\r")
412 .replace('\t', "\\t");
413 format!("'{escaped}'")
414 } else {
415 "null".to_string()
416 }
417 }
418 DataType::Array => {
419 #[allow(clippy::explicit_iter_loop)]
420 if let Some(arr) = zval.array() {
421 let is_sequential = arr.iter().enumerate().all(|(i, (key, _))| {
423 matches!(key, crate::types::ArrayKey::Long(idx) if i64::try_from(i).is_ok_and(|ii| idx == ii))
424 });
425
426 let mut parts = Vec::new();
427 for (key, val) in arr.iter() {
428 let val_str = zval_to_stub(val);
429 if is_sequential {
430 parts.push(val_str);
431 } else {
432 match key {
433 crate::types::ArrayKey::Long(idx) => {
434 parts.push(format!("{idx} => {val_str}"));
435 }
436 crate::types::ArrayKey::String(key) => {
437 let key_escaped = key.replace('\\', "\\\\").replace('\'', "\\'");
438 parts.push(format!("'{key_escaped}' => {val_str}"));
439 }
440 crate::types::ArrayKey::Str(key) => {
441 let key_escaped = key.replace('\\', "\\\\").replace('\'', "\\'");
442 parts.push(format!("'{key_escaped}' => {val_str}"));
443 }
444 crate::types::ArrayKey::ZendString(key) => {
445 let decoded = match key.as_str() {
446 Ok(s) => std::borrow::Cow::Borrowed(s),
447 Err(_) => String::from_utf8_lossy(key.as_bytes()),
448 };
449 let key_escaped =
450 decoded.replace('\\', "\\\\").replace('\'', "\\'");
451 parts.push(format!("'{key_escaped}' => {val_str}"));
452 }
453 }
454 }
455 }
456 format!("[{}]", parts.join(", "))
457 } else {
458 "[]".to_string()
459 }
460 }
461 _ => "null".to_string(),
462 }
463}
464
465impl<T: IntoZval + Clone> IntoZvalDyn for T {
466 fn as_zval(&self, persistent: bool) -> Result<Zval> {
467 self.clone().into_zval(persistent)
468 }
469
470 fn get_type(&self) -> DataType {
471 Self::TYPE
472 }
473}
474
475impl IntoZvalDyn for Zval {
476 fn as_zval(&self, _persistent: bool) -> Result<Zval> {
477 Ok(self.shallow_clone())
478 }
479
480 fn get_type(&self) -> DataType {
481 self.get_type()
482 }
483}
484
485pub trait StubLiteral {
493 fn stub_literal(&self) -> String;
495}
496
497macro_rules! stub_literal_display {
498 ($($ty:ty),*) => {
499 $(
500 impl StubLiteral for $ty {
501 fn stub_literal(&self) -> String {
502 self.to_string()
503 }
504 }
505 )*
506 };
507}
508
509stub_literal_display!(bool, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
510
511macro_rules! stub_literal_float {
512 ($($ty:ty),*) => {
513 $(
514 impl StubLiteral for $ty {
515 fn stub_literal(&self) -> String {
516 if self.is_nan() {
517 "NAN".to_string()
518 } else if self.is_infinite() {
519 if *self > 0.0 { "INF" } else { "-INF" }.to_string()
520 } else {
521 format!("{self:?}")
522 }
523 }
524 }
525 )*
526 };
527}
528
529stub_literal_float!(f32, f64);
530
531impl StubLiteral for str {
532 fn stub_literal(&self) -> String {
533 let escaped = self.replace('\\', "\\\\").replace('\'', "\\'");
534 format!("'{escaped}'")
535 }
536}
537
538impl StubLiteral for &str {
539 fn stub_literal(&self) -> String {
540 (**self).stub_literal()
541 }
542}
543
544impl StubLiteral for String {
545 fn stub_literal(&self) -> String {
546 self.as_str().stub_literal()
547 }
548}
549
550impl StubLiteral for std::borrow::Cow<'_, str> {
551 fn stub_literal(&self) -> String {
552 self.as_ref().stub_literal()
553 }
554}
555
556impl<T: StubLiteral> StubLiteral for Option<T> {
557 fn stub_literal(&self) -> String {
558 self.as_ref()
559 .map_or_else(|| "null".to_string(), StubLiteral::stub_literal)
560 }
561}
562
563impl<T: StubLiteral> StubLiteral for [T] {
564 fn stub_literal(&self) -> String {
565 let items: Vec<String> = self.iter().map(StubLiteral::stub_literal).collect();
566 format!("[{}]", items.join(", "))
567 }
568}
569
570impl<T: StubLiteral> StubLiteral for Vec<T> {
571 fn stub_literal(&self) -> String {
572 self.as_slice().stub_literal()
573 }
574}
575
576impl<T: StubLiteral, const N: usize> StubLiteral for [T; N] {
577 fn stub_literal(&self) -> String {
578 self.as_slice().stub_literal()
579 }
580}
581
582impl<K: StubLiteral, V: StubLiteral, S> StubLiteral for std::collections::HashMap<K, V, S> {
583 fn stub_literal(&self) -> String {
584 let mut entries: Vec<String> = self
585 .iter()
586 .map(|(key, value)| format!("{} => {}", key.stub_literal(), value.stub_literal()))
587 .collect();
588 entries.sort();
589 format!("[{}]", entries.join(", "))
590 }
591}
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596 use crate::types::{PhpRef, Separated, ZendHashTable, ZendObject};
597
598 const _: () = {
599 assert!(<Option<i64> as FromZval>::NULLABLE);
600 assert!(<Option<i64> as FromZvalMut>::NULLABLE);
601 assert!(!<i64 as FromZval>::NULLABLE);
602 assert!(!<i64 as FromZvalMut>::NULLABLE);
603 assert!(!<i64 as FromZvalMut>::BY_REF);
604 assert!(!<&Zval as FromZvalMut>::BY_REF);
605 assert!(<&mut Zval as FromZvalMut>::BY_REF);
606 assert!(<PhpRef<'_> as FromZvalMut>::BY_REF);
607 assert!(!<Separated<'_> as FromZvalMut>::BY_REF);
608 assert!(<&mut ZendHashTable as FromZvalMut>::BY_REF);
609 assert!(!<&mut ZendObject as FromZvalMut>::BY_REF);
610 };
611
612 #[test]
613 fn stub_literals_are_php_source() {
614 assert_eq!(42_i32.stub_literal(), "42");
615 assert_eq!(true.stub_literal(), "true");
616 assert_eq!(1.5_f64.stub_literal(), "1.5");
617 assert_eq!(3.0_f64.stub_literal(), "3.0");
618 assert_eq!(f64::INFINITY.stub_literal(), "INF");
619 assert_eq!("it's".stub_literal(), "'it\\'s'");
620 assert_eq!(String::from("a\\b").stub_literal(), "'a\\\\b'");
621 assert_eq!(None::<i64>.stub_literal(), "null");
622 assert_eq!(Some("x".to_string()).stub_literal(), "'x'");
623 assert_eq!(Vec::<i64>::new().stub_literal(), "[]");
624 assert_eq!(vec![1, 2].stub_literal(), "[1, 2]");
625 let map: std::collections::HashMap<&str, i64> = [("b", 2), ("a", 1)].into();
626 assert_eq!(map.stub_literal(), "['a' => 1, 'b' => 2]");
627 }
628
629 #[test]
630 fn omitted_argument_is_none_for_option_and_missing_otherwise() {
631 assert_eq!(<Option<i64> as FromZvalMut>::from_missing(), Some(None));
632 assert_eq!(
633 <Option<Option<i64>> as FromZvalMut>::from_missing(),
634 Some(None)
635 );
636 assert_eq!(<i64 as FromZvalMut>::from_missing(), None);
637 }
638
639 #[test]
640 #[cfg(feature = "embed")]
641 fn option_rejects_a_value_the_inner_type_rejects() {
642 assert_eq!(<Option<i64> as FromZval>::from_zval(&Zval::from(1.5)), None);
643 }
644
645 #[test]
646 #[cfg(feature = "embed")]
647 fn option_reads_null_as_none_unless_the_inner_type_accepts_null() {
648 assert_eq!(
649 <Option<i64> as FromZval>::from_zval(&Zval::new()),
650 Some(None)
651 );
652 assert_eq!(
653 <Option<Option<i64>> as FromZval>::from_zval(&Zval::new()),
654 Some(Some(None))
655 );
656 }
657}