Skip to main content

ext_php_rs/zend/
class.rs

1//! Builder and objects for creating classes in the PHP world.
2
3use crate::ffi::instanceof_function_slow;
4#[cfg(php84)]
5use crate::ffi::zend_class_can_be_lazy;
6use crate::types::{ZendIterator, Zval};
7use crate::{
8    boxed::ZBox,
9    convert::{FromZval, IntoZval},
10    error::{Error, Result},
11    ffi::{ZEND_RESULT_CODE_SUCCESS, zend_class_entry},
12    flags::ClassFlags,
13    types::{ZendObject, ZendStr},
14    zend::ExecutorGlobals,
15};
16use std::ffi::CString;
17use std::ptr;
18use std::{convert::TryInto, fmt::Debug};
19
20/// A PHP class entry.
21///
22/// Represents a class registered with the PHP interpreter.
23pub type ClassEntry = zend_class_entry;
24
25impl ClassEntry {
26    /// Attempts to find a reference to a class in the global class table.
27    ///
28    /// Returns a reference to the class if found, or [`None`] if the class
29    /// could not be found or the class table has not been initialized.
30    #[inline]
31    #[must_use]
32    pub fn try_find(name: &str) -> Option<&'static Self> {
33        ExecutorGlobals::get().class_table()?;
34        let mut name = ZendStr::new(name, false);
35
36        unsafe { crate::ffi::zend_lookup_class_ex(&raw mut *name, ptr::null_mut(), 0).as_ref() }
37    }
38
39    /// Creates a new [`ZendObject`], returned inside an [`ZBox<ZendObject>`]
40    /// wrapper.
41    ///
42    /// # Panics
43    ///
44    /// Panics when allocating memory for the new object fails.
45    #[allow(clippy::new_ret_no_self)]
46    #[must_use]
47    pub fn new(&self) -> ZBox<ZendObject> {
48        ZendObject::new(self)
49    }
50
51    /// Returns the class flags.
52    #[must_use]
53    pub fn flags(&self) -> ClassFlags {
54        ClassFlags::from_bits_truncate(self.ce_flags)
55    }
56
57    /// Returns `true` if the class entry is an interface, and `false`
58    /// otherwise.
59    #[must_use]
60    pub fn is_interface(&self) -> bool {
61        self.flags().contains(ClassFlags::Interface)
62    }
63
64    /// Returns `true` if instances of this class can be made lazy.
65    ///
66    /// Only user-defined classes and `stdClass` can be made lazy.
67    /// Internal classes (including Rust-defined classes) cannot be made lazy.
68    ///
69    /// This is a PHP 8.4+ feature.
70    #[cfg(php84)]
71    #[must_use]
72    pub fn can_be_lazy(&self) -> bool {
73        unsafe { zend_class_can_be_lazy(ptr::from_ref(self).cast_mut()) }
74    }
75
76    /// Checks if the class is an instance of another class or interface.
77    ///
78    /// # Parameters
79    ///
80    /// * `other` - The inherited class entry to check.
81    #[must_use]
82    pub fn instance_of(&self, other: &ClassEntry) -> bool {
83        if self == other {
84            return true;
85        }
86
87        unsafe { instanceof_function_slow(ptr::from_ref(self), ptr::from_ref(other)) }
88    }
89
90    /// Returns an iterator of all the interfaces that the class implements.
91    ///
92    /// Returns [`None`] if the interfaces have not been resolved on the
93    /// class.
94    ///
95    /// # Panics
96    ///
97    /// Panics if the number of interfaces exceeds `isize::MAX`.
98    #[must_use]
99    #[expect(
100        clippy::expect_used,
101        reason = "the interface count comes from the engine and fits in isize"
102    )]
103    pub fn interfaces(&self) -> Option<impl Iterator<Item = &ClassEntry>> {
104        self.flags()
105            .contains(ClassFlags::ResolvedInterfaces)
106            .then(|| unsafe {
107                (0..self.num_interfaces)
108                    .map(move |i| {
109                        *self
110                            .__bindgen_anon_3
111                            .interfaces
112                            .offset(isize::try_from(i).expect("index exceeds isize"))
113                    })
114                    .filter_map(|ptr| ptr.as_ref())
115            })
116    }
117
118    /// Returns the parent of the class.
119    ///
120    /// If the parent of the class has not been resolved, it attempts to find
121    /// the parent by name. Returns [`None`] if the parent was not resolved
122    /// and the parent was not able to be found by name.
123    #[must_use]
124    pub fn parent(&self) -> Option<&Self> {
125        if self.flags().contains(ClassFlags::ResolvedParent) {
126            unsafe { self.__bindgen_anon_1.parent.as_ref() }
127        } else {
128            let name = unsafe { self.__bindgen_anon_1.parent_name.as_ref()? };
129            Self::try_find(name.as_str().ok()?)
130        }
131    }
132
133    /// Returns the iterator for the class for a specific instance
134    ///
135    /// Returns [`None`] if there is no associated iterator for the class.
136    ///
137    /// Takes `zval` by mutable reference because the Zend `get_iterator` handler
138    /// may mutate the object it is called on, and the returned iterator aliases
139    /// it for `'a`.
140    #[must_use]
141    pub fn get_iterator<'a>(
142        &self,
143        zval: &'a mut Zval,
144        by_ref: bool,
145    ) -> Option<&'a mut ZendIterator> {
146        let ptr: *const Self = self;
147        let zval_ptr: *mut Zval = zval;
148
149        let iterator = unsafe { (*ptr).get_iterator?(ptr.cast_mut(), zval_ptr, i32::from(by_ref)) };
150
151        unsafe { iterator.as_mut() }
152    }
153
154    /// Gets the name of the class.
155    #[inline]
156    #[must_use]
157    pub fn name(&self) -> Option<&str> {
158        unsafe { self.name.as_ref().and_then(|s| s.as_str().ok()) }
159    }
160
161    /// Reads a static property from the class.
162    ///
163    /// # Parameters
164    ///
165    /// * `name` - The name of the static property to read.
166    ///
167    /// # Returns
168    ///
169    /// Returns the value of the static property if it exists and can be
170    /// converted to type `T`, or `None` otherwise.
171    ///
172    /// # Example
173    ///
174    /// ```no_run
175    /// use ext_php_rs::zend::ClassEntry;
176    ///
177    /// let ce = ClassEntry::try_find("MyClass").unwrap();
178    /// let value: Option<i64> = ce.get_static_property("counter");
179    /// ```
180    #[must_use]
181    pub fn get_static_property<'a, T: FromZval<'a>>(&'a self, name: &str) -> Option<T> {
182        let name = CString::new(name).ok()?;
183        let zval = unsafe {
184            crate::ffi::zend_read_static_property(
185                ptr::from_ref(self).cast_mut(),
186                name.as_ptr(),
187                name.as_bytes().len(),
188                true, // silent - don't throw if property doesn't exist
189            )
190            .as_ref()?
191        };
192        T::from_zval(zval)
193    }
194
195    /// Sets a static property on the class.
196    ///
197    /// # Parameters
198    ///
199    /// * `name` - The name of the static property to set.
200    /// * `value` - The value to set the property to.
201    ///
202    /// # Errors
203    ///
204    /// Returns an error if the property name contains a null byte, if the
205    /// value could not be converted to a Zval, or if the property could not
206    /// be updated (e.g., the property does not exist).
207    ///
208    /// # Example
209    ///
210    /// ```no_run
211    /// use ext_php_rs::zend::ClassEntry;
212    ///
213    /// let ce = ClassEntry::try_find("MyClass").unwrap();
214    /// ce.set_static_property("counter", 42).unwrap();
215    /// ```
216    pub fn set_static_property<T: IntoZval>(&self, name: &str, value: T) -> Result<()> {
217        let name = CString::new(name)?;
218        let mut zval = value.into_zval(false)?;
219        let result = unsafe {
220            crate::ffi::zend_update_static_property(
221                ptr::from_ref(self).cast_mut(),
222                name.as_ptr(),
223                name.as_bytes().len(),
224                &raw mut zval,
225            )
226        };
227        if result == ZEND_RESULT_CODE_SUCCESS {
228            Ok(())
229        } else {
230            Err(Error::InvalidProperty {
231                property: name.to_string_lossy().into_owned(),
232            })
233        }
234    }
235}
236
237impl PartialEq for ClassEntry {
238    fn eq(&self, other: &Self) -> bool {
239        std::ptr::eq(self, other)
240    }
241}
242
243impl Debug for ClassEntry {
244    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        let name: String = unsafe { self.name.as_ref() }
246            .and_then(|s| s.try_into().ok())
247            .ok_or(std::fmt::Error)?;
248
249        f.debug_struct("ClassEntry")
250            .field("name", &name)
251            .field("flags", &self.flags())
252            .field("is_interface", &self.is_interface())
253            .field(
254                "interfaces",
255                &self.interfaces().map(Iterator::collect::<Vec<_>>),
256            )
257            .field("parent", &self.parent())
258            .finish()
259    }
260}