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