ext_php_rs/
closure.rs

1//! Types and functions used for exporting Rust closures to PHP.
2
3use std::collections::HashMap;
4
5use crate::{
6    args::{Arg, ArgParser},
7    builders::{ClassBuilder, FunctionBuilder},
8    class::{ClassEntryInfo, ClassMetadata, RegisteredClass},
9    convert::{FromZval, IntoZval},
10    describe::DocComments,
11    exception::PhpException,
12    flags::{DataType, MethodFlags},
13    internal::property::PropertyInfo,
14    types::Zval,
15    zend::ExecuteData,
16    zend_fastcall,
17};
18
19/// Class entry and handlers for Rust closures.
20static CLOSURE_META: ClassMetadata<Closure> = ClassMetadata::new();
21
22/// Wrapper around a Rust closure, which can be exported to PHP.
23///
24/// Closures can have up to 8 parameters, all must implement [`FromZval`], and
25/// can return anything that implements [`IntoZval`]. Closures must have a
26/// static lifetime, and therefore cannot modify any `self` references.
27///
28/// Internally, closures are implemented as a PHP class. A class `RustClosure`
29/// is registered with an `__invoke` method:
30///
31/// ```php
32/// <?php
33///
34/// class RustClosure {
35///     public function __invoke(...$args): mixed {
36///         // ...
37///     }
38/// }
39/// ```
40///
41/// The Rust closure is then double boxed, firstly as a `Box<dyn Fn(...) ->
42/// ...>` (depending on the signature of the closure) and then finally boxed as
43/// a `Box<dyn PhpClosure>`. This is a workaround, as `PhpClosure` is not
44/// generically implementable on types that implement `Fn(T, ...) -> Ret`. Make
45/// a suggestion issue if you have a better idea of implementing this!.
46///
47/// When the `__invoke` method is called from PHP, the `invoke` method is called
48/// on the `dyn PhpClosure`\ trait object, and from there everything is
49/// basically the same as a regular PHP function.
50pub struct Closure(Box<dyn PhpClosure>);
51
52unsafe impl Send for Closure {}
53unsafe impl Sync for Closure {}
54
55impl Closure {
56    /// Wraps a [`Fn`] or [`FnMut`] Rust closure into a type which can be
57    /// returned to PHP.
58    ///
59    /// The closure can accept up to 8 arguments which implement [`IntoZval`],
60    /// and can return any type which implements [`FromZval`]. The closure
61    /// must have a static lifetime, so cannot reference `self`.
62    ///
63    /// # Parameters
64    ///
65    /// * `func` - The closure to wrap. Should be boxed in the form `Box<dyn
66    ///   Fn[Mut](...) -> ...>`.
67    ///
68    /// # Example
69    ///
70    /// ```rust,no_run
71    /// use ext_php_rs::closure::Closure;
72    ///
73    /// let closure = Closure::wrap(Box::new(|name| {
74    ///     format!("Hello {}", name)
75    /// }) as Box<dyn Fn(String) -> String>);
76    /// ```
77    pub fn wrap<T>(func: T) -> Self
78    where
79        T: PhpClosure + 'static,
80    {
81        Self(Box::new(func) as Box<dyn PhpClosure>)
82    }
83
84    /// Wraps a [`FnOnce`] Rust closure into a type which can be returned to
85    /// PHP. If the closure is called more than once from PHP, an exception
86    /// is thrown.
87    ///
88    /// The closure can accept up to 8 arguments which implement [`IntoZval`],
89    /// and can return any type which implements [`FromZval`]. The closure
90    /// must have a static lifetime, so cannot reference `self`.
91    ///
92    /// # Parameters
93    ///
94    /// * `func` - The closure to wrap. Should be boxed in the form `Box<dyn
95    ///   FnOnce(...) -> ...>`.
96    ///
97    /// # Example
98    ///
99    /// ```rust,no_run
100    /// use ext_php_rs::closure::Closure;
101    ///
102    /// let name: String = "Hello world".into();
103    /// let closure = Closure::wrap_once(Box::new(|| {
104    ///     name
105    /// }) as Box<dyn FnOnce() -> String>);
106    /// ```
107    pub fn wrap_once<T>(func: T) -> Self
108    where
109        T: PhpOnceClosure + 'static,
110    {
111        func.into_closure()
112    }
113
114    /// Builds the class entry for [`Closure`], registering it with PHP. This
115    /// function should only be called once inside your module startup
116    /// function.
117    ///
118    /// If the class has already been built, this function returns early without
119    /// doing anything. This allows for safe repeated calls in test environments.
120    ///
121    /// # Panics
122    ///
123    /// Panics if the `RustClosure` PHP class cannot be registered.
124    pub fn build() {
125        if CLOSURE_META.has_ce() {
126            return;
127        }
128
129        ClassBuilder::new("RustClosure")
130            .method(
131                FunctionBuilder::new("__invoke", Self::invoke)
132                    .not_required()
133                    .arg(Arg::new("args", DataType::Mixed).is_variadic())
134                    .returns(DataType::Mixed, false, true),
135                MethodFlags::Public,
136            )
137            .object_override::<Self>()
138            .registration(|ce| CLOSURE_META.set_ce(ce))
139            .register()
140            .expect("Failed to build `RustClosure` PHP class.");
141    }
142
143    zend_fastcall! {
144        /// External function used by the Zend interpreter to call the closure.
145        extern "C" fn invoke(ex: &mut ExecuteData, ret: &mut Zval) {
146            let (parser, this) = ex.parser_method::<Self>();
147            let this = this.expect("Internal closure function called on non-closure class");
148
149            this.0.invoke(parser, ret);
150        }
151    }
152}
153
154impl RegisteredClass for Closure {
155    const CLASS_NAME: &'static str = "RustClosure";
156
157    const BUILDER_MODIFIER: Option<fn(ClassBuilder) -> ClassBuilder> = None;
158    const EXTENDS: Option<ClassEntryInfo> = None;
159    const IMPLEMENTS: &'static [ClassEntryInfo] = &[];
160
161    fn get_metadata() -> &'static ClassMetadata<Self> {
162        &CLOSURE_META
163    }
164
165    fn get_properties<'a>() -> HashMap<&'static str, PropertyInfo<'a, Self>> {
166        HashMap::new()
167    }
168
169    fn method_builders() -> Vec<(FunctionBuilder<'static>, MethodFlags)> {
170        unimplemented!()
171    }
172
173    fn constructor() -> Option<crate::class::ConstructorMeta<Self>> {
174        None
175    }
176
177    fn constants() -> &'static [(
178        &'static str,
179        &'static dyn crate::convert::IntoZvalDyn,
180        DocComments,
181    )] {
182        unimplemented!()
183    }
184}
185
186class_derives!(Closure);
187
188/// Implemented on types which can be used as PHP closures.
189///
190/// Types must implement the `invoke` function which will be called when the
191/// closure is called from PHP. Arguments must be parsed from the
192/// [`ExecuteData`] and the return value is returned through the [`Zval`].
193///
194/// This trait is automatically implemented on functions with up to 8
195/// parameters.
196#[allow(clippy::missing_safety_doc)]
197pub unsafe trait PhpClosure {
198    /// Invokes the closure.
199    fn invoke<'a>(&'a mut self, parser: ArgParser<'a, '_>, ret: &mut Zval);
200}
201
202/// Implemented on [`FnOnce`] types which can be used as PHP closures. See
203/// [`Closure`].
204///
205/// Internally, this trait should wrap the [`FnOnce`] closure inside a [`FnMut`]
206/// closure, and prevent the user from calling the closure more than once.
207pub trait PhpOnceClosure {
208    /// Converts the Rust [`FnOnce`] closure into a [`FnMut`] closure, and then
209    /// into a PHP closure.
210    fn into_closure(self) -> Closure;
211}
212
213unsafe impl<R> PhpClosure for Box<dyn Fn() -> R>
214where
215    R: IntoZval,
216{
217    fn invoke(&mut self, _: ArgParser, ret: &mut Zval) {
218        if let Err(e) = self().set_zval(ret, false) {
219            let _ = PhpException::default(format!("Failed to return closure result to PHP: {e}"))
220                .throw();
221        }
222    }
223}
224
225unsafe impl<R> PhpClosure for Box<dyn FnMut() -> R>
226where
227    R: IntoZval,
228{
229    fn invoke(&mut self, _: ArgParser, ret: &mut Zval) {
230        if let Err(e) = self().set_zval(ret, false) {
231            let _ = PhpException::default(format!("Failed to return closure result to PHP: {e}"))
232                .throw();
233        }
234    }
235}
236
237impl<R> PhpOnceClosure for Box<dyn FnOnce() -> R>
238where
239    R: IntoZval + 'static,
240{
241    fn into_closure(self) -> Closure {
242        let mut this = Some(self);
243
244        Closure::wrap(Box::new(move || {
245            let Some(this) = this.take() else {
246                let _ = PhpException::default(
247                    "Attempted to call `FnOnce` closure more than once.".into(),
248                )
249                .throw();
250                return Option::<R>::None;
251            };
252
253            Some(this())
254        }) as Box<dyn FnMut() -> Option<R>>)
255    }
256}
257
258macro_rules! php_closure_impl {
259    ($($gen: ident),*) => {
260        php_closure_impl!(Fn; $($gen),*);
261        php_closure_impl!(FnMut; $($gen),*);
262
263        impl<$($gen),*, Ret> PhpOnceClosure for Box<dyn FnOnce($($gen),*) -> Ret>
264        where
265            $(for<'a> $gen: FromZval<'a> + 'static,)*
266            Ret: IntoZval + 'static,
267        {
268            fn into_closure(self) -> Closure {
269                let mut this = Some(self);
270
271                Closure::wrap(Box::new(move |$($gen),*| {
272                    let Some(this) = this.take() else {
273                        let _ = PhpException::default(
274                            "Attempted to call `FnOnce` closure more than once.".into(),
275                        )
276                        .throw();
277                        return Option::<Ret>::None;
278                    };
279
280                    Some(this($($gen),*))
281                }) as Box<dyn FnMut($($gen),*) -> Option<Ret>>)
282            }
283        }
284    };
285
286    ($fnty: ident; $($gen: ident),*) => {
287        unsafe impl<$($gen),*, Ret> PhpClosure for Box<dyn $fnty($($gen),*) -> Ret>
288        where
289            $(for<'a> $gen: FromZval<'a>,)*
290            Ret: IntoZval
291        {
292            fn invoke(&mut self, parser: ArgParser, ret: &mut Zval) {
293                $(
294                    let mut $gen = Arg::new(stringify!($gen), $gen::TYPE);
295                )*
296
297                let parser = parser
298                    $(.arg(&mut $gen))*
299                    .parse();
300
301                if parser.is_err() {
302                    return;
303                }
304
305                let result = self(
306                    $(
307                        match $gen.consume() {
308                            Ok(val) => val,
309                            _ => {
310                                let _ = PhpException::default(concat!("Invalid parameter type for `", stringify!($gen), "`.").into()).throw();
311                                return;
312                            }
313                        }
314                    ),*
315                );
316
317                if let Err(e) = result.set_zval(ret, false) {
318                    let _ = PhpException::default(format!("Failed to return closure result to PHP: {}", e)).throw();
319                }
320            }
321        }
322    };
323}
324
325php_closure_impl!(A);
326php_closure_impl!(A, B);
327php_closure_impl!(A, B, C);
328php_closure_impl!(A, B, C, D);
329php_closure_impl!(A, B, C, D, E);
330php_closure_impl!(A, B, C, D, E, F);
331php_closure_impl!(A, B, C, D, E, F, G);
332php_closure_impl!(A, B, C, D, E, F, G, H);