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