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 pub fn interfaces(&self) -> Option<impl Iterator<Item = &ClassEntry>> {
100 self.flags()
101 .contains(ClassFlags::ResolvedInterfaces)
102 .then(|| unsafe {
103 (0..self.num_interfaces)
104 .map(move |i| {
105 *self
106 .__bindgen_anon_3
107 .interfaces
108 .offset(isize::try_from(i).expect("index exceeds isize"))
109 })
110 .filter_map(|ptr| ptr.as_ref())
111 })
112 }
113
114 /// Returns the parent of the class.
115 ///
116 /// If the parent of the class has not been resolved, it attempts to find
117 /// the parent by name. Returns [`None`] if the parent was not resolved
118 /// and the parent was not able to be found by name.
119 #[must_use]
120 pub fn parent(&self) -> Option<&Self> {
121 if self.flags().contains(ClassFlags::ResolvedParent) {
122 unsafe { self.__bindgen_anon_1.parent.as_ref() }
123 } else {
124 let name = unsafe { self.__bindgen_anon_1.parent_name.as_ref()? };
125 Self::try_find(name.as_str().ok()?)
126 }
127 }
128
129 /// Returns the iterator for the class for a specific instance
130 ///
131 /// Returns [`None`] if there is no associated iterator for the class.
132 // TODO: Verify if this is safe to use, as it allows mutating the
133 // hashtable while only having a reference to it. #461
134 #[allow(clippy::mut_from_ref)]
135 #[must_use]
136 pub fn get_iterator<'a>(&self, zval: &'a Zval, by_ref: bool) -> Option<&'a mut ZendIterator> {
137 let ptr: *const Self = self;
138 let zval_ptr: *const Zval = zval;
139
140 let iterator =
141 unsafe { (*ptr).get_iterator?(ptr.cast_mut(), zval_ptr.cast_mut(), i32::from(by_ref)) };
142
143 unsafe { iterator.as_mut() }
144 }
145
146 /// Gets the name of the class.
147 #[inline]
148 #[must_use]
149 pub fn name(&self) -> Option<&str> {
150 unsafe { self.name.as_ref().and_then(|s| s.as_str().ok()) }
151 }
152
153 /// Reads a static property from the class.
154 ///
155 /// # Parameters
156 ///
157 /// * `name` - The name of the static property to read.
158 ///
159 /// # Returns
160 ///
161 /// Returns the value of the static property if it exists and can be
162 /// converted to type `T`, or `None` otherwise.
163 ///
164 /// # Example
165 ///
166 /// ```no_run
167 /// use ext_php_rs::zend::ClassEntry;
168 ///
169 /// let ce = ClassEntry::try_find("MyClass").unwrap();
170 /// let value: Option<i64> = ce.get_static_property("counter");
171 /// ```
172 #[must_use]
173 pub fn get_static_property<'a, T: FromZval<'a>>(&'a self, name: &str) -> Option<T> {
174 let name = CString::new(name).ok()?;
175 let zval = unsafe {
176 crate::ffi::zend_read_static_property(
177 ptr::from_ref(self).cast_mut(),
178 name.as_ptr(),
179 name.as_bytes().len(),
180 true, // silent - don't throw if property doesn't exist
181 )
182 .as_ref()?
183 };
184 T::from_zval(zval)
185 }
186
187 /// Sets a static property on the class.
188 ///
189 /// # Parameters
190 ///
191 /// * `name` - The name of the static property to set.
192 /// * `value` - The value to set the property to.
193 ///
194 /// # Errors
195 ///
196 /// Returns an error if the property name contains a null byte, if the
197 /// value could not be converted to a Zval, or if the property could not
198 /// be updated (e.g., the property does not exist).
199 ///
200 /// # Example
201 ///
202 /// ```no_run
203 /// use ext_php_rs::zend::ClassEntry;
204 ///
205 /// let ce = ClassEntry::try_find("MyClass").unwrap();
206 /// ce.set_static_property("counter", 42).unwrap();
207 /// ```
208 pub fn set_static_property<T: IntoZval>(&self, name: &str, value: T) -> Result<()> {
209 let name = CString::new(name)?;
210 let mut zval = value.into_zval(false)?;
211 let result = unsafe {
212 crate::ffi::zend_update_static_property(
213 ptr::from_ref(self).cast_mut(),
214 name.as_ptr(),
215 name.as_bytes().len(),
216 &raw mut zval,
217 )
218 };
219 if result == ZEND_RESULT_CODE_SUCCESS {
220 Ok(())
221 } else {
222 Err(Error::InvalidProperty)
223 }
224 }
225}
226
227impl PartialEq for ClassEntry {
228 fn eq(&self, other: &Self) -> bool {
229 std::ptr::eq(self, other)
230 }
231}
232
233impl Debug for ClassEntry {
234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 let name: String = unsafe { self.name.as_ref() }
236 .and_then(|s| s.try_into().ok())
237 .ok_or(std::fmt::Error)?;
238
239 f.debug_struct("ClassEntry")
240 .field("name", &name)
241 .field("flags", &self.flags())
242 .field("is_interface", &self.is_interface())
243 .field(
244 "interfaces",
245 &self.interfaces().map(Iterator::collect::<Vec<_>>),
246 )
247 .field("parent", &self.parent())
248 .finish()
249 }
250}