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