Skip to main content

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