ext_php_rs/class.rs
1//! Types and traits used for registering classes with PHP.
2
3use std::{
4 collections::HashMap,
5 marker::PhantomData,
6 sync::atomic::{AtomicPtr, Ordering},
7};
8
9use once_cell::sync::OnceCell;
10
11use crate::{
12 builders::{ClassBuilder, FunctionBuilder},
13 convert::IntoZvalDyn,
14 describe::DocComments,
15 exception::PhpException,
16 flags::{ClassFlags, MethodFlags, PropertyFlags},
17 internal::property::PropertyInfo,
18 zend::{ClassEntry, ExecuteData, ZendObjectHandlers},
19};
20
21/// A type alias for a tuple containing a function pointer to a class entry
22/// and a string representing the class name used in stubs.
23pub type ClassEntryInfo = (fn() -> &'static ClassEntry, &'static str);
24
25/// Implemented on Rust types which are exported to PHP. Allows users to get and
26/// set PHP properties on the object.
27pub trait RegisteredClass: Sized + 'static {
28 /// PHP class name of the registered class.
29 const CLASS_NAME: &'static str;
30
31 /// Function to be called when building the class. Allows user to modify the
32 /// class at runtime (add runtime constants etc).
33 const BUILDER_MODIFIER: Option<fn(ClassBuilder) -> ClassBuilder>;
34
35 /// Parent class entry. Optional.
36 const EXTENDS: Option<ClassEntryInfo>;
37
38 /// Interfaces implemented by the class.
39 const IMPLEMENTS: &'static [ClassEntryInfo];
40
41 /// PHP flags applied to the class.
42 const FLAGS: ClassFlags = ClassFlags::empty();
43
44 /// Doc comments for the class.
45 const DOC_COMMENTS: DocComments = &[];
46
47 /// Returns a reference to the class metadata, which stores the class entry
48 /// and handlers.
49 ///
50 /// This must be statically allocated, and is usually done through the
51 /// [`macro@php_class`] macro.
52 ///
53 /// [`macro@php_class`]: crate::php_class
54 fn get_metadata() -> &'static ClassMetadata<Self>;
55
56 /// Returns a hash table containing the properties of the class.
57 ///
58 /// The key should be the name of the property and the value should be a
59 /// reference to the property with reference to `self`. The value is a
60 /// [`PropertyInfo`].
61 ///
62 /// Instead of using this method directly, you should access the properties
63 /// through the [`ClassMetadata::get_properties`] function, which builds the
64 /// hashmap one and stores it in memory.
65 fn get_properties<'a>() -> HashMap<&'static str, PropertyInfo<'a, Self>>;
66
67 /// Returns the method builders required to build the class.
68 fn method_builders() -> Vec<(FunctionBuilder<'static>, MethodFlags)>;
69
70 /// Returns the class constructor (if any).
71 fn constructor() -> Option<ConstructorMeta<Self>>;
72
73 /// Returns the constants provided by the class.
74 fn constants() -> &'static [(&'static str, &'static dyn IntoZvalDyn, DocComments)];
75
76 /// Returns the static properties provided by the class.
77 ///
78 /// Static properties are declared at the class level and managed by PHP,
79 /// not by Rust handlers. Each tuple contains (name, flags, default, docs).
80 /// The default value is optional - `None` means null default.
81 #[must_use]
82 fn static_properties() -> &'static [(
83 &'static str,
84 PropertyFlags,
85 Option<&'static (dyn IntoZvalDyn + Sync)>,
86 DocComments,
87 )] {
88 &[]
89 }
90}
91
92/// Stores metadata about a classes Rust constructor, including the function
93/// pointer and the arguments of the function.
94pub struct ConstructorMeta<T> {
95 /// Constructor function.
96 pub constructor: fn(&mut ExecuteData) -> ConstructorResult<T>,
97 /// Function called to build the constructor function. Usually adds
98 /// arguments.
99 pub build_fn: fn(FunctionBuilder) -> FunctionBuilder,
100 /// Add constructor modification
101 pub flags: Option<MethodFlags>,
102}
103
104/// Result returned from a constructor of a class.
105pub enum ConstructorResult<T> {
106 /// Successfully constructed the class, contains the new class object.
107 Ok(T),
108 /// An exception occurred while constructing the class.
109 Exception(PhpException),
110 /// Invalid arguments were given to the constructor.
111 ArgError,
112}
113
114impl<T, E> From<std::result::Result<T, E>> for ConstructorResult<T>
115where
116 E: Into<PhpException>,
117{
118 fn from(result: std::result::Result<T, E>) -> Self {
119 match result {
120 Ok(x) => Self::Ok(x),
121 Err(e) => Self::Exception(e.into()),
122 }
123 }
124}
125
126impl<T> From<T> for ConstructorResult<T> {
127 fn from(result: T) -> Self {
128 Self::Ok(result)
129 }
130}
131
132/// Stores the class entry and handlers for a Rust type which has been exported
133/// to PHP. Usually allocated statically.
134pub struct ClassMetadata<T> {
135 handlers: OnceCell<ZendObjectHandlers>,
136 properties: OnceCell<HashMap<&'static str, PropertyInfo<'static, T>>>,
137 ce: AtomicPtr<ClassEntry>,
138
139 // `AtomicPtr` is used here because it is `Send + Sync`.
140 // fn() -> T could have been used but that is incompatible with const fns at
141 // the moment.
142 phantom: PhantomData<AtomicPtr<T>>,
143}
144
145impl<T> ClassMetadata<T> {
146 /// Creates a new class metadata instance.
147 #[must_use]
148 pub const fn new() -> Self {
149 Self {
150 handlers: OnceCell::new(),
151 properties: OnceCell::new(),
152 ce: AtomicPtr::new(std::ptr::null_mut()),
153 phantom: PhantomData,
154 }
155 }
156}
157
158impl<T> Default for ClassMetadata<T> {
159 fn default() -> Self {
160 Self::new()
161 }
162}
163
164impl<T: RegisteredClass> ClassMetadata<T> {
165 /// Returns an immutable reference to the object handlers contained inside
166 /// the class metadata.
167 pub fn handlers(&self) -> &ZendObjectHandlers {
168 self.handlers.get_or_init(ZendObjectHandlers::new::<T>)
169 }
170
171 /// Checks if the class entry has been stored, returning a boolean.
172 pub fn has_ce(&self) -> bool {
173 !self.ce.load(Ordering::SeqCst).is_null()
174 }
175
176 /// Retrieves a reference to the stored class entry.
177 ///
178 /// # Panics
179 ///
180 /// Panics if there is no class entry stored inside the class metadata.
181 pub fn ce(&self) -> &'static ClassEntry {
182 // SAFETY: There are only two values that can be stored in the atomic ptr: null
183 // or a static reference to a class entry. On the latter case,
184 // `as_ref()` will return `None` and the function will panic.
185 unsafe { self.ce.load(Ordering::SeqCst).as_ref() }
186 .expect("Attempted to retrieve class entry before it has been stored.")
187 }
188
189 /// Stores a reference to a class entry inside the class metadata.
190 ///
191 /// # Parameters
192 ///
193 /// * `ce` - The class entry to store.
194 ///
195 /// # Panics
196 ///
197 /// Panics if the class entry has already been set in the class metadata.
198 /// This function should only be called once.
199 pub fn set_ce(&self, ce: &'static mut ClassEntry) {
200 self.ce
201 .compare_exchange(
202 std::ptr::null_mut(),
203 ce,
204 Ordering::SeqCst,
205 Ordering::Relaxed,
206 )
207 .expect("Class entry has already been set");
208 }
209
210 /// Retrieves a reference to the hashmap storing the classes property
211 /// accessors.
212 ///
213 /// # Returns
214 ///
215 /// Immutable reference to the properties hashmap.
216 pub fn get_properties(&self) -> &HashMap<&'static str, PropertyInfo<'static, T>> {
217 self.properties.get_or_init(T::get_properties)
218 }
219}