ext_php_rs/zend/
class.rs

1//! Builder and objects for creating classes in the PHP world.
2
3use crate::ffi::instanceof_function_slow;
4use crate::types::{ZendIterator, Zval};
5use crate::{
6    boxed::ZBox,
7    ffi::zend_class_entry,
8    flags::ClassFlags,
9    types::{ZendObject, ZendStr},
10    zend::ExecutorGlobals,
11};
12use std::{convert::TryInto, fmt::Debug, ops::DerefMut};
13
14/// A PHP class entry.
15///
16/// Represents a class registered with the PHP interpreter.
17pub type ClassEntry = zend_class_entry;
18
19impl ClassEntry {
20    /// Attempts to find a reference to a class in the global class table.
21    ///
22    /// Returns a reference to the class if found, or [`None`] if the class
23    /// could not be found or the class table has not been initialized.
24    pub fn try_find(name: &str) -> Option<&'static Self> {
25        ExecutorGlobals::get().class_table()?;
26        let mut name = ZendStr::new(name, false);
27
28        unsafe {
29            crate::ffi::zend_lookup_class_ex(name.deref_mut(), std::ptr::null_mut(), 0).as_ref()
30        }
31    }
32
33    /// Creates a new [`ZendObject`], returned inside an [`ZBox<ZendObject>`]
34    /// wrapper.
35    ///
36    /// # Panics
37    ///
38    /// Panics when allocating memory for the new object fails.
39    #[allow(clippy::new_ret_no_self)]
40    pub fn new(&self) -> ZBox<ZendObject> {
41        ZendObject::new(self)
42    }
43
44    /// Returns the class flags.
45    pub fn flags(&self) -> ClassFlags {
46        ClassFlags::from_bits_truncate(self.ce_flags)
47    }
48
49    /// Returns `true` if the class entry is an interface, and `false`
50    /// otherwise.
51    pub fn is_interface(&self) -> bool {
52        self.flags().contains(ClassFlags::Interface)
53    }
54
55    /// Checks if the class is an instance of another class or interface.
56    ///
57    /// # Parameters
58    ///
59    /// * `other` - The inherited class entry to check.
60    pub fn instance_of(&self, other: &ClassEntry) -> bool {
61        if self == other {
62            return true;
63        }
64
65        unsafe { instanceof_function_slow(self as _, other as _) }
66    }
67
68    /// Returns an iterator of all the interfaces that the class implements.
69    ///
70    /// Returns [`None`] if the interfaces have not been resolved on the
71    /// class.
72    pub fn interfaces(&self) -> Option<impl Iterator<Item = &ClassEntry>> {
73        self.flags()
74            .contains(ClassFlags::ResolvedInterfaces)
75            .then(|| unsafe {
76                (0..self.num_interfaces)
77                    .map(move |i| *self.__bindgen_anon_3.interfaces.offset(i as _))
78                    .filter_map(|ptr| ptr.as_ref())
79            })
80    }
81
82    /// Returns the parent of the class.
83    ///
84    /// If the parent of the class has not been resolved, it attempts to find
85    /// the parent by name. Returns [`None`] if the parent was not resolved
86    /// and the parent was not able to be found by name.
87    pub fn parent(&self) -> Option<&Self> {
88        if self.flags().contains(ClassFlags::ResolvedParent) {
89            unsafe { self.__bindgen_anon_1.parent.as_ref() }
90        } else {
91            let name = unsafe { self.__bindgen_anon_1.parent_name.as_ref()? };
92            Self::try_find(name.as_str().ok()?)
93        }
94    }
95
96    /// Returns the iterator for the class for a specific instance
97    ///
98    /// Returns [`None`] if there is no associated iterator for the class.
99    pub fn get_iterator<'a>(&self, zval: &'a Zval, by_ref: bool) -> Option<&'a mut ZendIterator> {
100        let ptr: *const Self = self;
101        let zval_ptr: *const Zval = zval;
102
103        let iterator = unsafe {
104            (*ptr).get_iterator?(
105                ptr as *mut ClassEntry,
106                zval_ptr as *mut Zval,
107                if by_ref { 1 } else { 0 },
108            )
109        };
110
111        unsafe { iterator.as_mut() }
112    }
113
114    pub fn name(&self) -> Option<&str> {
115        unsafe { self.name.as_ref().and_then(|s| s.as_str().ok()) }
116    }
117}
118
119impl PartialEq for ClassEntry {
120    fn eq(&self, other: &Self) -> bool {
121        std::ptr::eq(self, other)
122    }
123}
124
125impl Debug for ClassEntry {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        let name: String = unsafe { self.name.as_ref() }
128            .and_then(|s| s.try_into().ok())
129            .ok_or(std::fmt::Error)?;
130
131        f.debug_struct("ClassEntry")
132            .field("name", &name)
133            .field("flags", &self.flags())
134            .field("is_interface", &self.is_interface())
135            .field(
136                "interfaces",
137                &self.interfaces().map(|iter| iter.collect::<Vec<_>>()),
138            )
139            .field("parent", &self.parent())
140            .finish()
141    }
142}