1use 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
14pub type ClassEntry = zend_class_entry;
18
19impl ClassEntry {
20 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 #[allow(clippy::new_ret_no_self)]
40 pub fn new(&self) -> ZBox<ZendObject> {
41 ZendObject::new(self)
42 }
43
44 pub fn flags(&self) -> ClassFlags {
46 ClassFlags::from_bits_truncate(self.ce_flags)
47 }
48
49 pub fn is_interface(&self) -> bool {
52 self.flags().contains(ClassFlags::Interface)
53 }
54
55 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 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 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 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}