Skip to main content

ext_php_rs/
convert.rs

1//! Traits used to convert between Zend/PHP and Rust types.
2
3use crate::{
4    boxed::ZBox,
5    error::{Error, Result},
6    exception::PhpException,
7    flags::DataType,
8    types::{ZendObject, Zval},
9};
10
11/// Allows zvals to be converted into Rust types in a fallible way. Reciprocal
12/// of the [`IntoZval`] trait.
13#[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    /// The corresponding type of the implemented value in PHP.
19    const TYPE: DataType;
20
21    /// Whether a PHP argument of this type accepts `null` and may be omitted.
22    ///
23    /// Drives the `?T` nullability bit and the optional position of a
24    /// parameter declared with this type.
25    const NULLABLE: bool = false;
26
27    /// Attempts to retrieve an instance of `Self` from a reference to a
28    /// [`Zval`].
29    ///
30    /// # Parameters
31    ///
32    /// * `zval` - Zval to get value from.
33    fn from_zval(zval: &'a Zval) -> Option<Self>;
34
35    /// The value to use when a PHP argument of this type was omitted by the
36    /// caller. `None` means the argument is required.
37    ///
38    /// It must return `Some` exactly when `NULLABLE` is `true`. The macros
39    /// decide from `NULLABLE` alone which parameters PHP callers may omit.
40    #[must_use]
41    fn from_missing() -> Option<Self> {
42        None
43    }
44
45    /// Attempts to retrieve an instance of `Self` from a reference to a
46    /// [`Zval`], and tells why it failed.
47    ///
48    /// # Errors
49    ///
50    /// * [`Error::ZvalConversion`] - The value is not a `Self`.
51    /// * [`Error::Borrow`] - The value is a class object whose Rust value is
52    ///   borrowed. The implementations for `ClassRef<T>` and `ClassRefMut<T>`
53    ///   return this error.
54    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/// Allows mutable zvals to be converted into Rust types in a fallible way.
86///
87/// If `Self` does not require the zval to be mutable to be extracted, you
88/// should implement [`FromZval`] instead, as this trait is generically
89/// implemented for any type that implements [`FromZval`].
90#[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    /// The corresponding type of the implemented value in PHP.
98    const TYPE: DataType;
99
100    /// Whether a PHP argument of this type accepts `null` and may be omitted.
101    const NULLABLE: bool = false;
102
103    /// Whether a PHP argument of this type is declared pass-by-reference
104    /// (`&$arg`). Set it for types that mutate a PHP value in place, so the
105    /// engine separates the value before the call.
106    const BY_REF: bool = false;
107
108    /// Attempts to retrieve an instance of `Self` from a mutable reference to a
109    /// [`Zval`].
110    ///
111    /// # Parameters
112    ///
113    /// * `zval` - Zval to get value from.
114    fn from_zval_mut(zval: &'a mut Zval) -> Option<Self>;
115
116    /// The value to use when a PHP argument of this type was omitted by the
117    /// caller. `None` means the argument is required.
118    ///
119    /// It must return `Some` exactly when `NULLABLE` is `true`. The macros
120    /// decide from `NULLABLE` alone which parameters PHP callers may omit.
121    #[must_use]
122    fn from_missing() -> Option<Self> {
123        None
124    }
125
126    /// Attempts to retrieve an instance of `Self` from a mutable reference to a
127    /// [`Zval`], and tells why it failed.
128    ///
129    /// # Errors
130    ///
131    /// * [`Error::ZvalConversion`] - The value is not a `Self`.
132    /// * [`Error::Borrow`] - The value is a class object whose Rust value is
133    ///   borrowed. A [`FromZval`] type gives the error of
134    ///   [`FromZval::try_from_zval`].
135    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
164/// `FromZendObject` is implemented by types which can be extracted from a Zend
165/// object.
166///
167/// Normal usage is through the helper method `ZendObject::extract`:
168///
169/// ```rust,ignore
170/// let obj: ZendObject = ...;
171/// let repr: String = obj.extract();
172/// let props: HashMap = obj.extract();
173/// ```
174///
175/// Should be functionally equivalent to casting an object to another compatible
176/// type.
177pub trait FromZendObject<'a>: Sized {
178    /// Extracts `Self` from the source `ZendObject`.
179    ///
180    /// # Errors
181    ///
182    /// * [`Error::ZvalConversion`] - If the object is not of the expected
183    ///   class.
184    /// * [`Error::InvalidProperty`] - If a property the conversion needs is
185    ///   missing.
186    ///
187    /// [`Error::ZvalConversion`]: crate::error::Error::ZvalConversion
188    /// [`Error::InvalidProperty`]: crate::error::Error::InvalidProperty
189    fn from_zend_object(obj: &'a ZendObject) -> Result<Self>;
190}
191
192/// Implemented on types which can be extracted from a mutable zend object.
193///
194/// If `Self` does not require the object to be mutable, it should implement
195/// [`FromZendObject`] instead, as this trait is generically implemented for
196/// any types that also implement [`FromZendObject`].
197pub trait FromZendObjectMut<'a>: Sized {
198    /// Extracts `Self` from the source `ZendObject`.
199    ///
200    /// # Errors
201    ///
202    /// * [`Error::ZvalConversion`] - If the object is not of the expected
203    ///   class.
204    /// * [`Error::InvalidProperty`] - If a property the conversion needs is
205    ///   missing.
206    ///
207    /// [`Error::ZvalConversion`]: crate::error::Error::ZvalConversion
208    /// [`Error::InvalidProperty`]: crate::error::Error::InvalidProperty
209    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
222/// Implemented on types which can be converted into a Zend object. It is up to
223/// the implementation to determine the type of object which is produced.
224pub trait IntoZendObject {
225    /// Attempts to convert `self` into a Zend object.
226    ///
227    /// # Errors
228    ///
229    /// * [`Error::ZvalConversion`] - If the value has no object
230    ///   representation.
231    /// * [`Error::InvalidScope`] - If the class of the object has not been
232    ///   registered with the engine.
233    ///
234    /// [`Error::ZvalConversion`]: crate::error::Error::ZvalConversion
235    /// [`Error::InvalidScope`]: crate::error::Error::InvalidScope
236    fn into_zend_object(self) -> Result<ZBox<ZendObject>>;
237}
238
239/// Provides implementations for converting Rust primitive types into PHP zvals.
240/// Alternative to the built-in Rust [`From`] and [`TryFrom`] implementations,
241/// allowing the caller to specify whether the Zval contents will persist
242/// between requests.
243///
244/// [`TryFrom`]: std::convert::TryFrom
245pub trait IntoZval: Sized {
246    /// The corresponding type of the implemented value in PHP.
247    const TYPE: DataType;
248
249    /// Whether converting into a [`Zval`] may result in null.
250    const NULLABLE: bool;
251
252    /// Converts a Rust primitive type into a Zval. Returns a result containing
253    /// the Zval if successful.
254    ///
255    /// # Parameters
256    ///
257    /// * `persistent` - Whether the contents of the Zval will persist between
258    ///   requests.
259    ///
260    /// # Errors
261    ///
262    /// Implementations return the error that describes their failure, for
263    /// example:
264    ///
265    /// * [`Error::IntegerOverflow`] - If the value does not fit in a PHP
266    ///   integer.
267    /// * [`Error::InvalidCString`] - If a string in the value contains a NUL
268    ///   byte.
269    ///
270    /// [`Error::IntegerOverflow`]: crate::error::Error::IntegerOverflow
271    /// [`Error::InvalidCString`]: crate::error::Error::InvalidCString
272    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    /// Sets the content of a pre-existing zval. Returns a result containing
279    /// nothing if setting the content was successful.
280    ///
281    /// # Parameters
282    ///
283    /// * `zv` - The Zval to set the content of.
284    /// * `persistent` - Whether the contents of the Zval will persist between
285    ///   requests.
286    ///
287    /// # Errors
288    ///
289    /// Implementations return the error that describes their failure, for
290    /// example:
291    ///
292    /// * [`Error::IntegerOverflow`] - If the value does not fit in a PHP
293    ///   integer.
294    /// * [`Error::InvalidCString`] - If a string in the value contains a NUL
295    ///   byte.
296    ///
297    /// [`Error::IntegerOverflow`]: crate::error::Error::IntegerOverflow
298    /// [`Error::InvalidCString`]: crate::error::Error::InvalidCString
299    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
351/// An object-safe version of the [`IntoZval`] trait.
352///
353/// This trait is automatically implemented on any type that implements both
354/// [`IntoZval`] and [`Clone`]. You avoid implementing this trait directly,
355/// rather implement these two other traits.
356pub trait IntoZvalDyn {
357    /// Converts a Rust primitive type into a Zval. Returns a result containing
358    /// the Zval if successful. `self` is cloned before being converted into
359    /// a zval.
360    ///
361    /// # Parameters
362    ///
363    /// * `persistent` - Whether the contents of the Zval will persist between
364    ///   requests.
365    ///
366    /// # Errors
367    ///
368    /// If the conversion fails, an [`Error`] is returned.
369    ///
370    /// [`Error`]: crate::error::Error
371    fn as_zval(&self, persistent: bool) -> Result<Zval>;
372
373    /// Returns the PHP type of the type.
374    fn get_type(&self) -> DataType;
375
376    /// Returns the PHP stub representation of this value.
377    ///
378    /// This is used when generating PHP stub files for IDE autocompletion.
379    /// The returned string should be a valid PHP literal.
380    fn stub_value(&self) -> String {
381        // Default implementation - convert to zval and format
382        match self.as_zval(false) {
383            Ok(zval) => zval_to_stub(&zval),
384            Err(_) => "null".to_string(),
385        }
386    }
387}
388
389/// Converts a Zval to its PHP stub representation.
390#[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                // Check if array has sequential numeric keys starting from 0
422                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
485/// Renders a Rust value as PHP source, for the `default_value` of a parameter
486/// and for stub files.
487///
488/// The rendering never touches the engine, so it can run while the module
489/// entry is built, before the Zend allocator exists. PHP reads the text back
490/// with `zend_get_default_from_internal_arg_info`, which accepts `null`,
491/// `true`, `false`, integers, quoted strings, `[]` and constant expressions.
492pub trait StubLiteral {
493    /// The PHP source text of this value.
494    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}