ext-php-rs 0.15.9

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use std::{ffi::CString, mem::MaybeUninit, ptr, rc::Rc};

use crate::{
    builders::FunctionBuilder,
    class::{ClassEntryInfo, ConstructorMeta, ConstructorResult, RegisteredClass},
    convert::{IntoZval, IntoZvalDyn},
    describe::DocComments,
    error::{Error, Result},
    exception::PhpException,
    ffi::{
        zend_declare_class_constant, zend_declare_property, zend_do_implement_interface,
        zend_register_internal_class_ex, zend_register_internal_interface,
    },
    flags::{ClassFlags, DataType, MethodFlags, PropertyFlags},
    types::{ZendClassObject, ZendObject, ZendStr, Zval},
    zend::{ClassEntry, ExecuteData, FunctionEntry},
    zend_fastcall,
};

/// A constant entry: (name, `value_closure`, docs, `stub_value`)
type ConstantEntry = (
    String,
    Box<dyn FnOnce() -> Result<Zval>>,
    DocComments,
    String,
);
type PropertyDefault = Option<Box<dyn FnOnce() -> Result<Zval>>>;

/// Metadata for a class property to be registered with PHP.
pub struct ClassProperty {
    /// Name of the property.
    pub name: String,
    /// Visibility and modifier flags.
    pub flags: PropertyFlags,
    /// Optional default value closure.
    pub default: PropertyDefault,
    /// Documentation comments.
    pub docs: DocComments,
    /// PHP type for stub generation.
    pub ty: Option<DataType>,
    /// Whether the property accepts null.
    pub nullable: bool,
    /// Whether the property is read-only (getter without setter).
    pub readonly: bool,
    /// PHP stub representation of the default value (e.g. `"null"`, `"42"`).
    pub default_stub: Option<String>,
}

/// Builder for registering a class in PHP.
#[must_use]
pub struct ClassBuilder {
    pub(crate) name: String,
    ce: ClassEntry,
    pub(crate) extends: Option<ClassEntryInfo>,
    pub(crate) interfaces: Vec<ClassEntryInfo>,
    pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
    object_override: Option<unsafe extern "C" fn(class_type: *mut ClassEntry) -> *mut ZendObject>,
    pub(crate) properties: Vec<ClassProperty>,
    pub(crate) constants: Vec<ConstantEntry>,
    register: Option<fn(&'static mut ClassEntry)>,
    pub(crate) docs: DocComments,
}

impl ClassBuilder {
    /// Creates a new class builder, used to build classes
    /// to be exported to PHP.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the class.
    pub fn new<T: Into<String>>(name: T) -> Self {
        Self {
            name: name.into(),
            // SAFETY: A zeroed class entry is in an initialized state, as it is a raw C type
            // whose fields do not have a drop implementation.
            ce: unsafe { MaybeUninit::zeroed().assume_init() },
            extends: None,
            interfaces: vec![],
            methods: vec![],
            object_override: None,
            properties: vec![],
            constants: vec![],
            register: None,
            docs: &[],
        }
    }

    /// Return PHP class flags
    #[must_use]
    pub fn get_flags(&self) -> u32 {
        self.ce.ce_flags
    }

    /// Sets the class builder to extend another class.
    ///
    /// # Parameters
    ///
    /// * `parent` - The parent class to extend.
    pub fn extends(mut self, parent: ClassEntryInfo) -> Self {
        self.extends = Some(parent);
        self
    }

    /// Implements an interface on the class.
    ///
    /// # Parameters
    ///
    /// * `interface` - Interface to implement on the class.
    ///
    /// # Panics
    ///
    /// Panics when the given class entry `interface` is not an interface.
    pub fn implements(mut self, interface: ClassEntryInfo) -> Self {
        self.interfaces.push(interface);
        self
    }

    /// Adds a method to the class.
    ///
    /// # Parameters
    ///
    /// * `func` - The function builder to add to the class.
    /// * `flags` - Flags relating to the function. See [`MethodFlags`].
    pub fn method(mut self, func: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
        self.methods.push((func, flags));
        self
    }

    /// Adds a property to the class.
    ///
    /// # Parameters
    ///
    /// * `prop` - The property metadata to add to the class.
    pub fn property(mut self, prop: ClassProperty) -> Self {
        self.properties.push(prop);
        self
    }

    /// Adds a constant to the class. The type of the constant is defined by the
    /// type of the given default.
    ///
    /// Returns a result containing the class builder if the constant was
    /// successfully added.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the constant to add to the class.
    /// * `value` - The value of the constant.
    /// * `docs` - Documentation comments for the constant.
    ///
    /// # Errors
    ///
    /// TODO: Never?
    pub fn constant<T: Into<String>>(
        mut self,
        name: T,
        value: impl IntoZval + 'static,
        docs: DocComments,
    ) -> Result<Self> {
        // Convert to Zval first to get stub value
        let zval = value.into_zval(true)?;
        let stub = crate::convert::zval_to_stub(&zval);
        self.constants
            .push((name.into(), Box::new(|| Ok(zval)), docs, stub));
        Ok(self)
    }

    /// Adds a constant to the class from a `dyn` object. The type of the
    /// constant is defined by the type of the value.
    ///
    /// Returns a result containing the class builder if the constant was
    /// successfully added.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the constant to add to the class.
    /// * `value` - The value of the constant.
    /// * `docs` - Documentation comments for the constant.
    ///
    /// # Errors
    ///
    /// TODO: Never?
    pub fn dyn_constant<T: Into<String>>(
        mut self,
        name: T,
        value: &'static dyn IntoZvalDyn,
        docs: DocComments,
    ) -> Result<Self> {
        let stub = value.stub_value();
        let value = Rc::new(value);
        self.constants.push((
            name.into(),
            Box::new(move || value.as_zval(true)),
            docs,
            stub,
        ));
        Ok(self)
    }

    /// Sets the flags for the class.
    ///
    /// # Parameters
    ///
    /// * `flags` - Flags relating to the class. See [`ClassFlags`].
    pub fn flags(mut self, flags: ClassFlags) -> Self {
        self.ce.ce_flags = flags.bits();
        self
    }

    /// Overrides the creation of the Zend object which will represent an
    /// instance of this class.
    ///
    /// # Parameters
    ///
    /// * `T` - The type which will override the Zend object. Must implement
    ///   [`RegisteredClass`] which can be derived using the
    ///   [`php_class`](crate::php_class) attribute macro.
    ///
    /// # Panics
    ///
    /// Panics if the class name associated with `T` is not the same as the
    /// class name specified when creating the builder.
    pub fn object_override<T: RegisteredClass>(mut self) -> Self {
        extern "C" fn create_object<T: RegisteredClass>(ce: *mut ClassEntry) -> *mut ZendObject {
            // Try to initialize with a default instance if available.
            // This is critical for exception classes that extend \Exception, because
            // PHP's zend_throw_exception_ex creates objects via create_object without
            // calling the constructor, then immediately accesses properties.
            // Without default initialization, accessing properties on uninitialized
            // objects would panic.
            if let Some(instance) = T::default_init() {
                let obj = ZendClassObject::<T>::new(instance);
                return obj.into_raw().get_mut_zend_obj();
            }

            // SAFETY: After calling this function, PHP will always call the constructor
            // defined below, which assumes that the object is uninitialized.
            let obj = unsafe { ZendClassObject::<T>::new_uninit(ce.as_ref()) };
            obj.into_raw().get_mut_zend_obj()
        }

        zend_fastcall! {
            extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
                use crate::zend::try_catch;
                use std::panic::AssertUnwindSafe;

                // Wrap the constructor body with try_catch to ensure Rust destructors
                // are called if a bailout occurs (issue #537)
                let catch_result = try_catch(AssertUnwindSafe(|| {
                    let Some(ConstructorMeta { constructor, .. }) = T::constructor() else {
                        PhpException::default("You cannot instantiate this class from PHP.".into())
                            .throw()
                            .expect("Failed to throw exception when constructing class");
                        return;
                    };

                    let this = match constructor(ex) {
                        ConstructorResult::Ok(this) => this,
                        ConstructorResult::Exception(e) => {
                            e.throw()
                                .expect("Failed to throw exception while constructing class");
                            return;
                        }
                        ConstructorResult::ArgError => return,
                    };

                    // Use get_object_uninit because the Rust backing is not yet initialized.
                    // We need access to the ZendClassObject to call initialize() on it.
                    let Some(this_obj) = ex.get_object_uninit::<T>() else {
                        PhpException::default("Failed to retrieve reference to `this` object.".into())
                            .throw()
                            .expect("Failed to throw exception while constructing class");
                        return;
                    };

                    this_obj.initialize(this);
                }));

                // If there was a bailout, re-trigger it after Rust cleanup
                if catch_result.is_err() {
                    unsafe { crate::zend::bailout(); }
                }
            }
        }

        debug_assert_eq!(
            self.name.as_str(),
            T::CLASS_NAME,
            "Class name in builder does not match class name in `impl RegisteredClass`."
        );
        self.object_override = Some(create_object::<T>);
        let is_interface = T::FLAGS.contains(ClassFlags::Interface);

        // For interfaces: only add __construct if explicitly declared
        // For classes: always add __construct (PHP needs it for object creation)
        if let Some(ConstructorMeta {
            build_fn, flags, ..
        }) = T::constructor()
        {
            let func = if is_interface {
                FunctionBuilder::new_abstract("__construct")
            } else {
                FunctionBuilder::new("__construct", constructor::<T>)
            };
            let visibility = flags.unwrap_or(MethodFlags::Public);
            self.method(build_fn(func), visibility)
        } else if is_interface {
            // Don't add default constructor for interfaces
            self
        } else {
            // Add default constructor for classes
            let func = FunctionBuilder::new("__construct", constructor::<T>);
            self.method(func, MethodFlags::Public)
        }
    }

    /// Function to register the class with PHP. This function is called after
    /// the class is built.
    ///
    /// # Parameters
    ///
    /// * `register` - The function to call to register the class.
    pub fn registration(mut self, register: fn(&'static mut ClassEntry)) -> Self {
        self.register = Some(register);
        self
    }

    /// Sets the documentation for the class.
    ///
    /// # Parameters
    ///
    /// * `docs` - The documentation comments for the class.
    pub fn docs(mut self, docs: DocComments) -> Self {
        self.docs = docs;
        self
    }

    /// Builds and registers the class.
    ///
    /// # Errors
    ///
    /// * [`Error::InvalidPointer`] - If the class could not be registered.
    /// * [`Error::InvalidCString`] - If the class name is not a valid C string.
    /// * [`Error::IntegerOverflow`] - If the property flags are not valid.
    /// * If a method or property could not be built.
    ///
    /// # Panics
    ///
    /// If no registration function was provided.
    pub fn register(mut self) -> Result<()> {
        self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();

        let mut methods = self
            .methods
            .into_iter()
            .map(|(method, flags)| {
                method.build().map(|mut method| {
                    method.flags |= flags.bits();
                    method
                })
            })
            .collect::<Result<Vec<_>>>()?;

        methods.push(FunctionEntry::end());
        let func = Box::into_raw(methods.into_boxed_slice()) as *const FunctionEntry;
        self.ce.info.internal.builtin_functions = func;

        let class = if self.ce.flags().contains(ClassFlags::Interface) {
            unsafe {
                zend_register_internal_interface(&raw mut self.ce)
                    .as_mut()
                    .ok_or(Error::InvalidPointer)?
            }
        } else {
            unsafe {
                zend_register_internal_class_ex(
                    &raw mut self.ce,
                    match self.extends {
                        Some((ptr, _)) => ptr::from_ref(ptr()).cast_mut(),
                        None => std::ptr::null_mut(),
                    },
                )
                .as_mut()
                .ok_or(Error::InvalidPointer)?
            }
        };

        // disable serialization if the class has an associated object
        if self.object_override.is_some() {
            cfg_if::cfg_if! {
                if #[cfg(php81)] {
                    class.ce_flags |= ClassFlags::NotSerializable.bits();
                } else {
                    class.serialize = Some(crate::ffi::zend_class_serialize_deny);
                    class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
                }
            }
        }

        for (iface, _) in self.interfaces {
            let interface = iface();
            assert!(
                interface.is_interface(),
                "Given class entry was not an interface."
            );

            unsafe { zend_do_implement_interface(class, ptr::from_ref(interface).cast_mut()) };
        }

        for prop in self.properties {
            let mut default_zval = match prop.default {
                Some(f) => f()?,
                None => Zval::new(),
            };
            unsafe {
                zend_declare_property(
                    class,
                    CString::new(prop.name.as_str())?.as_ptr(),
                    prop.name.len() as _,
                    &raw mut default_zval,
                    prop.flags.bits().try_into()?,
                );
            }
        }

        for (name, value, _, _) in self.constants {
            let value = Box::into_raw(Box::new(value()?));
            unsafe {
                zend_declare_class_constant(
                    class,
                    CString::new(name.as_str())?.as_ptr(),
                    name.len(),
                    value,
                );
            };
        }

        if let Some(object_override) = self.object_override {
            class.__bindgen_anon_2.create_object = Some(object_override);
        }

        if let Some(register) = self.register {
            register(class);
        } else {
            panic!("Class {} was not registered.", self.name);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::test::test_function;

    use super::*;

    #[test]
    #[allow(unpredictable_function_pointer_comparisons)]
    fn test_new() {
        let class = ClassBuilder::new("Foo");
        assert_eq!(class.name, "Foo");
        assert_eq!(class.extends, None);
        assert_eq!(class.interfaces, vec![]);
        assert_eq!(class.methods.len(), 0);
        assert_eq!(class.object_override, None);
        assert!(class.properties.is_empty());
        assert_eq!(class.constants.len(), 0);
        assert_eq!(class.register, None);
        assert_eq!(class.docs, &[] as DocComments);
    }

    #[test]
    fn test_extends() {
        let extends: ClassEntryInfo = (|| todo!(), "Bar");
        let class = ClassBuilder::new("Foo").extends(extends);
        assert_eq!(class.extends, Some(extends));
    }

    #[test]
    fn test_implements() {
        let implements: ClassEntryInfo = (|| todo!(), "Bar");
        let class = ClassBuilder::new("Foo").implements(implements);
        assert_eq!(class.interfaces, vec![implements]);
    }

    #[test]
    fn test_method() {
        let method = FunctionBuilder::new("foo", test_function);
        let class = ClassBuilder::new("Foo").method(method, MethodFlags::Public);
        assert_eq!(class.methods.len(), 1);
    }

    #[test]
    fn test_property() {
        let class = ClassBuilder::new("Foo").property(ClassProperty {
            name: "bar".into(),
            flags: PropertyFlags::Public,
            default: None,
            docs: &["Doc 1"],
            ty: Some(DataType::String),
            nullable: false,
            readonly: false,
            default_stub: None,
        });
        assert_eq!(class.properties.len(), 1);
        assert_eq!(class.properties[0].name, "bar");
        assert_eq!(class.properties[0].flags, PropertyFlags::Public);
        assert!(class.properties[0].default.is_none());
        assert_eq!(class.properties[0].docs, &["Doc 1"] as DocComments);
        assert_eq!(class.properties[0].ty, Some(DataType::String));
    }

    #[test]
    #[cfg(feature = "embed")]
    fn test_constant() {
        let class = ClassBuilder::new("Foo")
            .constant("bar", 42, &["Doc 1"])
            .expect("Failed to create constant");
        assert_eq!(class.constants.len(), 1);
        assert_eq!(class.constants[0].0, "bar");
        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
    }

    #[test]
    #[cfg(feature = "embed")]
    fn test_dyn_constant() {
        let class = ClassBuilder::new("Foo")
            .dyn_constant("bar", &42, &["Doc 1"])
            .expect("Failed to create constant");
        assert_eq!(class.constants.len(), 1);
        assert_eq!(class.constants[0].0, "bar");
        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
    }

    #[test]
    fn test_flags() {
        let class = ClassBuilder::new("Foo").flags(ClassFlags::Abstract);
        assert_eq!(class.ce.ce_flags, ClassFlags::Abstract.bits());
    }

    #[test]
    fn test_registration() {
        let class = ClassBuilder::new("Foo").registration(|_| {});
        assert!(class.register.is_some());
    }

    #[test]
    fn test_registration_interface() {
        let class = ClassBuilder::new("Foo")
            .flags(ClassFlags::Interface)
            .registration(|_| {});
        assert!(class.register.is_some());
    }

    #[test]
    fn test_docs() {
        let class = ClassBuilder::new("Foo").docs(&["Doc 1"]);
        assert_eq!(class.docs, &["Doc 1"] as DocComments);
    }

    // TODO: Test the register function
}