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},
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
77/// Stores metadata about a classes Rust constructor, including the function
78/// pointer and the arguments of the function.
79pub struct ConstructorMeta<T> {
80 /// Constructor function.
81 pub constructor: fn(&mut ExecuteData) -> ConstructorResult<T>,
82 /// Function called to build the constructor function. Usually adds
83 /// arguments.
84 pub build_fn: fn(FunctionBuilder) -> FunctionBuilder,
85 /// Add constructor modification
86 pub flags: Option<MethodFlags>,
87}
88
89/// Result returned from a constructor of a class.
90pub enum ConstructorResult<T> {
91 /// Successfully constructed the class, contains the new class object.
92 Ok(T),
93 /// An exception occurred while constructing the class.
94 Exception(PhpException),
95 /// Invalid arguments were given to the constructor.
96 ArgError,
97}
98
99impl<T, E> From<std::result::Result<T, E>> for ConstructorResult<T>
100where
101 E: Into<PhpException>,
102{
103 fn from(result: std::result::Result<T, E>) -> Self {
104 match result {
105 Ok(x) => Self::Ok(x),
106 Err(e) => Self::Exception(e.into()),
107 }
108 }
109}
110
111impl<T> From<T> for ConstructorResult<T> {
112 fn from(result: T) -> Self {
113 Self::Ok(result)
114 }
115}
116
117/// Stores the class entry and handlers for a Rust type which has been exported
118/// to PHP. Usually allocated statically.
119pub struct ClassMetadata<T> {
120 handlers: OnceCell<ZendObjectHandlers>,
121 properties: OnceCell<HashMap<&'static str, PropertyInfo<'static, T>>>,
122 ce: AtomicPtr<ClassEntry>,
123
124 // `AtomicPtr` is used here because it is `Send + Sync`.
125 // fn() -> T could have been used but that is incompatible with const fns at
126 // the moment.
127 phantom: PhantomData<AtomicPtr<T>>,
128}
129
130impl<T> ClassMetadata<T> {
131 /// Creates a new class metadata instance.
132 #[must_use]
133 pub const fn new() -> Self {
134 Self {
135 handlers: OnceCell::new(),
136 properties: OnceCell::new(),
137 ce: AtomicPtr::new(std::ptr::null_mut()),
138 phantom: PhantomData,
139 }
140 }
141}
142
143impl<T> Default for ClassMetadata<T> {
144 fn default() -> Self {
145 Self::new()
146 }
147}
148
149impl<T: RegisteredClass> ClassMetadata<T> {
150 /// Returns an immutable reference to the object handlers contained inside
151 /// the class metadata.
152 pub fn handlers(&self) -> &ZendObjectHandlers {
153 self.handlers.get_or_init(ZendObjectHandlers::new::<T>)
154 }
155
156 /// Checks if the class entry has been stored, returning a boolean.
157 pub fn has_ce(&self) -> bool {
158 !self.ce.load(Ordering::SeqCst).is_null()
159 }
160
161 /// Retrieves a reference to the stored class entry.
162 ///
163 /// # Panics
164 ///
165 /// Panics if there is no class entry stored inside the class metadata.
166 pub fn ce(&self) -> &'static ClassEntry {
167 // SAFETY: There are only two values that can be stored in the atomic ptr: null
168 // or a static reference to a class entry. On the latter case,
169 // `as_ref()` will return `None` and the function will panic.
170 unsafe { self.ce.load(Ordering::SeqCst).as_ref() }
171 .expect("Attempted to retrieve class entry before it has been stored.")
172 }
173
174 /// Stores a reference to a class entry inside the class metadata.
175 ///
176 /// # Parameters
177 ///
178 /// * `ce` - The class entry to store.
179 ///
180 /// # Panics
181 ///
182 /// Panics if the class entry has already been set in the class metadata.
183 /// This function should only be called once.
184 pub fn set_ce(&self, ce: &'static mut ClassEntry) {
185 self.ce
186 .compare_exchange(
187 std::ptr::null_mut(),
188 ce,
189 Ordering::SeqCst,
190 Ordering::Relaxed,
191 )
192 .expect("Class entry has already been set");
193 }
194
195 /// Retrieves a reference to the hashmap storing the classes property
196 /// accessors.
197 ///
198 /// # Returns
199 ///
200 /// Immutable reference to the properties hashmap.
201 pub fn get_properties(&self) -> &HashMap<&'static str, PropertyInfo<'static, T>> {
202 self.properties.get_or_init(T::get_properties)
203 }
204}