Skip to main content

ext_php_rs/builders/
class.rs

1use std::{
2    ffi::CString,
3    mem::{ManuallyDrop, MaybeUninit},
4    ptr,
5    rc::Rc,
6};
7
8use crate::{
9    args::ArgInfoTables,
10    builders::{FunctionBuilder, function::free_registered_entries},
11    class::{ClassEntryInfo, ConstructorMeta, ConstructorResult, RegisteredClass},
12    convert::{IntoZval, IntoZvalDyn},
13    describe::DocComments,
14    error::{Error, Result},
15    exception::PhpException,
16    ffi::{
17        zend_declare_class_constant_ex, zend_declare_property, zend_do_implement_interface,
18        zend_hash_str_find_ptr_lc, zend_register_internal_class_ex,
19        zend_register_internal_interface,
20    },
21    flags::{ClassFlags, ConstantFlags, DataType, MethodFlags, PropertyFlags},
22    types::{ZendClassObject, ZendObject, ZendStr, Zval},
23    zend::function::{SensitiveParameters, mark_sensitive},
24    zend::{ClassEntry, CompilerGlobals, ExecuteData, ExecutorGlobals, FunctionEntry},
25    zend_fastcall,
26};
27
28/// A constant entry: (name, `value_closure`, docs, `stub_value`, flags)
29type ConstantEntry = (
30    String,
31    Box<dyn FnOnce() -> Result<Zval>>,
32    DocComments,
33    String,
34    ConstantFlags,
35);
36type PropertyDefault = Option<Box<dyn FnOnce() -> Result<Zval>>>;
37
38/// Metadata for a class property to be registered with PHP.
39pub struct ClassProperty {
40    /// Name of the property.
41    pub name: String,
42    /// Visibility and modifier flags.
43    pub flags: PropertyFlags,
44    /// Optional default value closure.
45    pub default: PropertyDefault,
46    /// Documentation comments.
47    pub docs: DocComments,
48    /// PHP type for stub generation.
49    pub ty: Option<DataType>,
50    /// Whether the property accepts null.
51    pub nullable: bool,
52    /// Whether the property is read-only (getter without setter).
53    pub readonly: bool,
54    /// PHP stub representation of the default value (e.g. `"null"`, `"42"`).
55    pub default_stub: Option<String>,
56}
57
58/// Returns the first name that repeats an earlier one. The engine keys
59/// method, function and class tables by ASCII-lowercased name, and constant and
60/// property tables by the exact name.
61pub(crate) fn first_duplicate<'a>(
62    names: impl IntoIterator<Item = &'a str>,
63    fold_ascii_case: bool,
64) -> Option<&'a str> {
65    let names: Vec<&str> = names.into_iter().collect();
66    names.iter().enumerate().find_map(|(i, name)| {
67        names[..i]
68            .iter()
69            .any(|earlier| {
70                if fold_ascii_case {
71                    earlier.eq_ignore_ascii_case(name)
72                } else {
73                    earlier == name
74                }
75            })
76            .then_some(*name)
77    })
78}
79
80/// Returns an error when the engine already holds a class, interface or enum
81/// named `name`, ignoring ASCII case. `do_register_internal_class` would
82/// silently replace it.
83///
84/// `EG(class_table)` is only set at request startup, so this reads
85/// `CG(class_table)`, which holds every class registered so far.
86pub(crate) fn ensure_class_name_free(name: &str) -> Result<()> {
87    let class_table = CompilerGlobals::get().class_table;
88    if class_table.is_null() {
89        return Ok(());
90    }
91    // SAFETY: `class_table` is the engine's live class table and `name` is
92    // valid for `name.len()` bytes; the lookup copies it before lowercasing.
93    let found = unsafe { zend_hash_str_find_ptr_lc(class_table, name.as_ptr().cast(), name.len()) };
94    if found.is_null() {
95        Ok(())
96    } else {
97        Err(Error::DuplicateClass {
98            class: name.to_owned(),
99        })
100    }
101}
102
103/// Builder for registering a class in PHP.
104#[must_use]
105pub struct ClassBuilder {
106    pub(crate) name: String,
107    ce: ClassEntry,
108    pub(crate) extends: Option<ClassEntryInfo>,
109    pub(crate) interfaces: Vec<ClassEntryInfo>,
110    pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
111    object_override: Option<unsafe extern "C" fn(class_type: *mut ClassEntry) -> *mut ZendObject>,
112    pub(crate) properties: Vec<ClassProperty>,
113    pub(crate) constants: Vec<ConstantEntry>,
114    register: Option<fn(&'static mut ClassEntry, ArgInfoTables)>,
115    pub(crate) docs: DocComments,
116}
117
118impl ClassBuilder {
119    /// Creates a new class builder, used to build classes
120    /// to be exported to PHP.
121    ///
122    /// # Parameters
123    ///
124    /// * `name` - The name of the class.
125    pub fn new<T: Into<String>>(name: T) -> Self {
126        Self {
127            name: name.into(),
128            // SAFETY: A zeroed class entry is in an initialized state, as it is a raw C type
129            // whose fields do not have a drop implementation.
130            ce: unsafe { MaybeUninit::zeroed().assume_init() },
131            extends: None,
132            interfaces: vec![],
133            methods: vec![],
134            object_override: None,
135            properties: vec![],
136            constants: vec![],
137            register: None,
138            docs: &[],
139        }
140    }
141
142    /// Return PHP class flags
143    #[must_use]
144    pub fn get_flags(&self) -> u32 {
145        self.ce.ce_flags
146    }
147
148    /// Sets the class builder to extend another class.
149    ///
150    /// # Parameters
151    ///
152    /// * `parent` - The parent class to extend.
153    pub fn extends(mut self, parent: ClassEntryInfo) -> Self {
154        self.extends = Some(parent);
155        self
156    }
157
158    /// Implements an interface on the class.
159    ///
160    /// # Parameters
161    ///
162    /// * `interface` - Interface to implement on the class.
163    ///
164    /// # Panics
165    ///
166    /// Panics when the given class entry `interface` is not an interface.
167    pub fn implements(mut self, interface: ClassEntryInfo) -> Self {
168        self.interfaces.push(interface);
169        self
170    }
171
172    /// Adds a method to the class.
173    ///
174    /// # Parameters
175    ///
176    /// * `func` - The function builder to add to the class.
177    /// * `flags` - Flags relating to the function. See [`MethodFlags`].
178    pub fn method(mut self, func: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
179        self.methods.push((func, flags));
180        self
181    }
182
183    /// Adds a property to the class.
184    ///
185    /// # Parameters
186    ///
187    /// * `prop` - The property metadata to add to the class.
188    pub fn property(mut self, prop: ClassProperty) -> Self {
189        self.properties.push(prop);
190        self
191    }
192
193    /// Adds a constant to the class. The type of the constant is defined by the
194    /// type of the given default.
195    ///
196    /// Returns a result containing the class builder if the constant was
197    /// successfully added.
198    ///
199    /// # Parameters
200    ///
201    /// * `name` - The name of the constant to add to the class.
202    /// * `value` - The value of the constant.
203    /// * `docs` - Documentation comments for the constant.
204    /// * `flags` - Visibility of the constant.
205    ///
206    /// # Errors
207    ///
208    /// Returns an error if `value` cannot be converted into a [`Zval`].
209    pub fn constant<T: Into<String>>(
210        mut self,
211        name: T,
212        value: impl IntoZval + 'static,
213        docs: DocComments,
214        flags: ConstantFlags,
215    ) -> Result<Self> {
216        let zval = value.into_zval(true)?;
217        let stub = crate::convert::zval_to_stub(&zval);
218        self.constants
219            .push((name.into(), Box::new(|| Ok(zval)), docs, stub, flags));
220        Ok(self)
221    }
222
223    /// Adds a constant to the class from a `dyn` object. The type of the
224    /// constant is defined by the type of the value.
225    ///
226    /// Returns a result containing the class builder if the constant was
227    /// successfully added.
228    ///
229    /// # Parameters
230    ///
231    /// * `name` - The name of the constant to add to the class.
232    /// * `value` - The value of the constant.
233    /// * `docs` - Documentation comments for the constant.
234    /// * `flags` - Visibility of the constant.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if `value` cannot be converted into a [`Zval`].
239    pub fn dyn_constant<T: Into<String>>(
240        mut self,
241        name: T,
242        value: &'static dyn IntoZvalDyn,
243        docs: DocComments,
244        flags: ConstantFlags,
245    ) -> Result<Self> {
246        let stub = value.stub_value();
247        let value = Rc::new(value);
248        self.constants.push((
249            name.into(),
250            Box::new(move || value.as_zval(true)),
251            docs,
252            stub,
253            flags,
254        ));
255        Ok(self)
256    }
257
258    /// Sets the flags for the class.
259    ///
260    /// # Parameters
261    ///
262    /// * `flags` - Flags relating to the class. See [`ClassFlags`].
263    pub fn flags(mut self, flags: ClassFlags) -> Self {
264        self.ce.ce_flags = flags.bits();
265        self
266    }
267
268    /// Overrides the creation of the Zend object which will represent an
269    /// instance of this class.
270    ///
271    /// # Parameters
272    ///
273    /// * `T` - The type which will override the Zend object. Must implement
274    ///   [`RegisteredClass`] which can be derived using the
275    ///   [`php_class`](crate::php_class) attribute macro.
276    ///
277    /// # Panics
278    ///
279    /// Panics if the class name associated with `T` is not the same as the
280    /// class name specified when creating the builder.
281    pub fn object_override<T: RegisteredClass>(mut self) -> Self {
282        extern "C" fn create_object<T: RegisteredClass>(ce: *mut ClassEntry) -> *mut ZendObject {
283            // Try to initialize with a default instance if available.
284            // This is critical for exception classes that extend \Exception, because
285            // PHP's zend_throw_exception_ex creates objects via create_object without
286            // calling the constructor, then immediately accesses properties.
287            // Without default initialization, accessing properties on uninitialized
288            // objects would panic.
289            if let Some(instance) = T::default_init() {
290                let obj = ZendClassObject::<T>::new(instance).into_raw();
291                // SAFETY: `into_raw` yields a valid, exclusively owned object that
292                // the engine takes over.
293                return unsafe { (*obj).get_mut_zend_obj() };
294            }
295
296            // SAFETY: After calling this function, PHP will always call the constructor
297            // defined below, which assumes that the object is uninitialized.
298            let obj = unsafe { ZendClassObject::<T>::new_uninit(ce.as_ref()) }.into_raw();
299            // SAFETY: same ownership transfer as above.
300            unsafe { (*obj).get_mut_zend_obj() }
301        }
302
303        zend_fastcall! {
304            extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
305                crate::zend::run_handler(std::panic::AssertUnwindSafe(|| {
306                    let Some(ConstructorMeta { constructor, .. }) = T::constructor() else {
307                        PhpException::from_message("You cannot instantiate this class from PHP.".into())
308                            .throw();
309                        return;
310                    };
311
312                    let this = match constructor(ex) {
313                        ConstructorResult::Ok(this) => this,
314                        ConstructorResult::Exception(e) => {
315                            e.throw();
316                            return;
317                        }
318                        ConstructorResult::ArgError => return,
319                    };
320
321                    // Use get_object_uninit because the Rust backing is not yet initialized.
322                    // We need access to the ZendClassObject to call initialize() on it.
323                    let Some(this_obj) = ex.get_object_uninit::<T>() else {
324                        PhpException::from_message("Failed to retrieve reference to `this` object.".into())
325                            .throw();
326                        return;
327                    };
328
329                    this_obj.initialize(this);
330                }));
331            }
332        }
333
334        debug_assert_eq!(
335            self.name.as_str(),
336            T::CLASS_NAME,
337            "Class name in builder does not match class name in `impl RegisteredClass`."
338        );
339        self.object_override = Some(create_object::<T>);
340        let is_interface = T::FLAGS.contains(ClassFlags::Interface);
341
342        // For interfaces: only add __construct if explicitly declared
343        // For classes: always add __construct (PHP needs it for object creation)
344        if let Some(ConstructorMeta {
345            build_fn, flags, ..
346        }) = T::constructor()
347        {
348            let func = if is_interface {
349                FunctionBuilder::new_abstract("__construct")
350            } else {
351                FunctionBuilder::new("__construct", constructor::<T>)
352            };
353            let visibility = flags.unwrap_or(MethodFlags::Public);
354            self.method(build_fn(func), visibility)
355        } else if is_interface {
356            // Don't add default constructor for interfaces
357            self
358        } else {
359            // Add default constructor for classes
360            let func = FunctionBuilder::new("__construct", constructor::<T>);
361            self.method(func, MethodFlags::Public)
362        }
363    }
364
365    /// Function to register the class with PHP, called once the class is built.
366    ///
367    /// It receives the registered class entry and the argument info tables of
368    /// the class's methods. `zend_register_functions` borrows those tables for
369    /// the life of the process, so the function must park them somewhere that
370    /// lives that long — normally the class's own
371    /// [`ClassMetadata`](crate::class::ClassMetadata) static:
372    ///
373    /// ```rust,ignore
374    /// .registration(|ce, arg_info| {
375    ///     META.set_ce(ce);
376    ///     META.set_arg_info(arg_info);
377    /// })
378    /// ```
379    ///
380    /// # Parameters
381    ///
382    /// * `register` - The function to call to register the class.
383    pub fn registration(mut self, register: fn(&'static mut ClassEntry, ArgInfoTables)) -> Self {
384        self.register = Some(register);
385        self
386    }
387
388    /// Sets the documentation for the class.
389    ///
390    /// # Parameters
391    ///
392    /// * `docs` - The documentation comments for the class.
393    pub fn docs(mut self, docs: DocComments) -> Self {
394        self.docs = docs;
395        self
396    }
397
398    /// Checks that no two properties, methods or constants of the class share
399    /// a PHP name. Methods are compared ignoring ASCII case, like the engine.
400    fn validate(&self) -> Result<()> {
401        if let Some(name) = first_duplicate(self.properties.iter().map(|p| p.name.as_str()), false)
402        {
403            return Err(Error::DuplicateProperty {
404                property: format!("{}::${name}", self.name),
405            });
406        }
407        if let Some(name) = first_duplicate(self.methods.iter().map(|(m, _)| m.name.as_str()), true)
408        {
409            return Err(Error::DuplicateMethod {
410                method: format!("{}::{name}", self.name),
411            });
412        }
413        if let Some(name) = first_duplicate(self.constants.iter().map(|c| c.0.as_str()), false) {
414            return Err(Error::DuplicateConstant {
415                constant: format!("{}::{name}", self.name),
416            });
417        }
418        Ok(())
419    }
420
421    /// Builds and registers the class.
422    ///
423    /// # Errors
424    ///
425    /// * [`Error::DuplicateProperty`], [`Error::DuplicateMethod`] or
426    ///   [`Error::DuplicateConstant`] - If two members share a PHP name.
427    /// * [`Error::DuplicateClass`] - If a class with this name, ignoring ASCII
428    ///   case, is already registered.
429    /// * [`Error::InvalidPointer`] - If the class could not be registered.
430    /// * [`Error::InvalidCString`] - If the class name is not a valid C string.
431    /// * [`Error::IntegerOverflow`] - If the property flags are not valid.
432    /// * If a method or property could not be built.
433    ///
434    /// # Panics
435    ///
436    /// * If called outside a module startup (MINIT) function.
437    /// * If no registration function was provided.
438    pub fn register(mut self) -> Result<()> {
439        assert!(
440            !ExecutorGlobals::get().current_module.is_null(),
441            "Classes can only be registered from a module startup (MINIT) function: \
442             `do_register_internal_class` dereferences `EG(current_module)`."
443        );
444        self.validate()?;
445        ensure_class_name_free(&self.name)?;
446
447        self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();
448
449        let mut arg_info = Vec::with_capacity(self.methods.len());
450        let mut methods = Vec::with_capacity(self.methods.len() + 1);
451        let mut sensitive = SensitiveParameters::new();
452        for (method, flags) in self.methods {
453            sensitive.extend(method.sensitive());
454            let (mut entry, args) = method.build()?;
455            entry.add_flags(flags);
456            methods.push(entry);
457            arg_info.push(args);
458        }
459
460        // The engine keeps `zend_internal_function.arg_info` pointing into these
461        // for the life of the process, so `register` parks them. Holding them in
462        // a `ManuallyDrop` keeps them alive across registration, which reads
463        // them, without a second owner. Every fallible step below runs after the
464        // class entry is in `CG(class_table)`, so an error must leak the tables
465        // rather than dangle the functions the engine already holds.
466        let arg_info = ManuallyDrop::new(arg_info.into_boxed_slice());
467
468        methods.push(FunctionEntry::end());
469        let entries = Box::into_raw(methods.into_boxed_slice());
470        self.ce.info.internal.builtin_functions = entries.cast::<FunctionEntry>().cast_const();
471
472        let class = if self.ce.flags().contains(ClassFlags::Interface) {
473            unsafe { zend_register_internal_interface(&raw mut self.ce) }
474        } else {
475            // Resolved here and not before the branch: the getter is usually
476            // `T::get_metadata().ce()`, which panics when the parent has not been
477            // registered, and `zend_register_internal_interface` takes no parent.
478            let parent = match self.extends {
479                Some((ptr, _)) => ptr::from_ref(ptr()).cast_mut(),
480                None => std::ptr::null_mut(),
481            };
482            unsafe { zend_register_internal_class_ex(&raw mut self.ce, parent) }
483        };
484
485        // SAFETY: `do_register_internal_class` has interned every `fname` and read
486        // `builtin_functions` for the last time, so the table is dead.
487        unsafe { free_registered_entries(entries) };
488
489        let class = unsafe { class.as_mut() }.ok_or(Error::InvalidPointer)?;
490        class.info.internal.builtin_functions = ptr::null();
491        mark_sensitive(&raw const class.function_table, &sensitive);
492
493        // disable serialization if the class has an associated object
494        if self.object_override.is_some() {
495            cfg_if::cfg_if! {
496                if #[cfg(php81)] {
497                    class.ce_flags |= ClassFlags::NotSerializable.bits();
498                } else {
499                    class.serialize = Some(crate::ffi::zend_class_serialize_deny);
500                    class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
501                }
502            }
503        }
504
505        for (iface, _) in self.interfaces {
506            let interface = iface();
507            assert!(
508                interface.is_interface(),
509                "Given class entry was not an interface."
510            );
511
512            unsafe { zend_do_implement_interface(class, ptr::from_ref(interface).cast_mut()) };
513        }
514
515        for prop in self.properties {
516            let mut default_zval = match prop.default {
517                Some(f) => f()?,
518                None => Zval::new(),
519            };
520            unsafe {
521                zend_declare_property(
522                    class,
523                    CString::new(prop.name.as_str())?.as_ptr(),
524                    prop.name.len() as _,
525                    &raw mut default_zval,
526                    prop.flags.bits().try_into()?,
527                );
528            }
529        }
530
531        for (name, value, _, _, flags) in self.constants {
532            // The constants table keeps the interned key; releasing an interned
533            // string is a no-op, so dropping the `ZBox` afterwards is sound.
534            let name = ZendStr::new_interned(&name, true);
535            // `zend_declare_class_constant_ex` takes the payload with
536            // `ZVAL_COPY_VALUE` and no incref and, unlike
537            // `zend_declare_typed_property`, does not reject refcounted values, so
538            // the constants table owns it and the `Zval` must not run its destructor.
539            let mut value = ManuallyDrop::new(value()?);
540            unsafe {
541                zend_declare_class_constant_ex(
542                    class,
543                    name.as_ptr().cast_mut(),
544                    &raw mut *value,
545                    flags.bits().try_into()?,
546                    ptr::null_mut(),
547                );
548            };
549        }
550
551        if let Some(object_override) = self.object_override {
552            class.__bindgen_anon_2.create_object = Some(object_override);
553        }
554
555        if let Some(register) = self.register {
556            register(class, ManuallyDrop::into_inner(arg_info));
557        } else {
558            panic!("Class {} was not registered.", self.name);
559        }
560
561        Ok(())
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use crate::test::test_function;
568
569    use super::*;
570
571    #[test]
572    #[allow(unpredictable_function_pointer_comparisons)]
573    fn test_new() {
574        let class = ClassBuilder::new("Foo");
575        assert_eq!(class.name, "Foo");
576        assert_eq!(class.extends, None);
577        assert_eq!(class.interfaces, vec![]);
578        assert_eq!(class.methods.len(), 0);
579        assert_eq!(class.object_override, None);
580        assert!(class.properties.is_empty());
581        assert_eq!(class.constants.len(), 0);
582        assert_eq!(class.register, None);
583        assert_eq!(class.docs, &[] as DocComments);
584    }
585
586    #[test]
587    fn test_extends() {
588        let extends: ClassEntryInfo = (|| todo!(), "Bar");
589        let class = ClassBuilder::new("Foo").extends(extends);
590        assert_eq!(class.extends, Some(extends));
591    }
592
593    #[test]
594    fn test_implements() {
595        let implements: ClassEntryInfo = (|| todo!(), "Bar");
596        let class = ClassBuilder::new("Foo").implements(implements);
597        assert_eq!(class.interfaces, vec![implements]);
598    }
599
600    #[test]
601    fn test_method() {
602        let method = FunctionBuilder::new("foo", test_function);
603        let class = ClassBuilder::new("Foo").method(method, MethodFlags::Public);
604        assert_eq!(class.methods.len(), 1);
605    }
606
607    #[test]
608    fn test_property() {
609        let class = ClassBuilder::new("Foo").property(ClassProperty {
610            name: "bar".into(),
611            flags: PropertyFlags::Public,
612            default: None,
613            docs: &["Doc 1"],
614            ty: Some(DataType::String),
615            nullable: false,
616            readonly: false,
617            default_stub: None,
618        });
619        assert_eq!(class.properties.len(), 1);
620        assert_eq!(class.properties[0].name, "bar");
621        assert_eq!(class.properties[0].flags, PropertyFlags::Public);
622        assert!(class.properties[0].default.is_none());
623        assert_eq!(class.properties[0].docs, &["Doc 1"] as DocComments);
624        assert_eq!(class.properties[0].ty, Some(DataType::String));
625    }
626
627    fn named_property(name: &str) -> ClassProperty {
628        ClassProperty {
629            name: name.into(),
630            flags: PropertyFlags::Public,
631            default: None,
632            docs: &[],
633            ty: None,
634            nullable: false,
635            readonly: false,
636            default_stub: None,
637        }
638    }
639
640    fn with_constant(mut class: ClassBuilder, name: &str) -> ClassBuilder {
641        class.constants.push((
642            name.into(),
643            Box::new(|| Err(Error::InvalidPointer)),
644            &[],
645            String::new(),
646            ConstantFlags::Public,
647        ));
648        class
649    }
650
651    #[test]
652    fn first_duplicate_folds_ascii_case_only_when_asked() {
653        assert_eq!(first_duplicate(["a", "b", "a"], false), Some("a"));
654        assert_eq!(first_duplicate(["a", "B", "b"], false), None);
655        assert_eq!(first_duplicate(["a", "B", "b"], true), Some("b"));
656        assert_eq!(first_duplicate(["ä", "Ä"], true), None);
657        assert_eq!(first_duplicate([], true), None);
658    }
659
660    #[test]
661    fn validate_rejects_a_repeated_property() {
662        let mut class = ClassBuilder::new("Foo");
663        class.properties = vec![named_property("a"), named_property("a")];
664        assert!(matches!(
665            class.validate(),
666            Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
667        ));
668    }
669
670    #[test]
671    fn validate_rejects_methods_that_differ_only_by_case() {
672        let class = ClassBuilder::new("Foo")
673            .method(
674                FunctionBuilder::new("run", test_function),
675                MethodFlags::Public,
676            )
677            .method(
678                FunctionBuilder::new("RUN", test_function),
679                MethodFlags::Static,
680            );
681        assert!(matches!(
682            class.validate(),
683            Err(Error::DuplicateMethod { method }) if method == "Foo::RUN"
684        ));
685    }
686
687    #[test]
688    fn validate_compares_constants_exactly() {
689        let class = with_constant(with_constant(ClassBuilder::new("Foo"), "A"), "a");
690        assert!(class.validate().is_ok());
691        let class = with_constant(class, "A");
692        assert!(matches!(
693            class.validate(),
694            Err(Error::DuplicateConstant { constant }) if constant == "Foo::A"
695        ));
696    }
697
698    #[test]
699    #[cfg(feature = "embed")]
700    fn class_names_already_in_the_class_table_are_taken() {
701        let ran = crate::embed::Embed::run(|| {
702            assert!(matches!(
703                ensure_class_name_free("STDCLASS"),
704                Err(Error::DuplicateClass { class }) if class == "STDCLASS"
705            ));
706            assert!(ensure_class_name_free("ExtPhpRsNoSuchClass").is_ok());
707            true
708        });
709        assert!(ran);
710    }
711
712    #[test]
713    fn validate_accepts_distinct_members() {
714        let mut class = ClassBuilder::new("Foo")
715            .method(
716                FunctionBuilder::new("run", test_function),
717                MethodFlags::Public,
718            )
719            .method(
720                FunctionBuilder::new("stop", test_function),
721                MethodFlags::Public,
722            );
723        class.properties = vec![named_property("a"), named_property("b")];
724        assert!(with_constant(class, "A").validate().is_ok());
725    }
726
727    #[test]
728    #[cfg(feature = "embed")]
729    fn test_constant() {
730        let class = ClassBuilder::new("Foo")
731            .constant("bar", 42, &["Doc 1"], ConstantFlags::Public)
732            .expect("Failed to create constant");
733        assert_eq!(class.constants.len(), 1);
734        assert_eq!(class.constants[0].0, "bar");
735        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
736    }
737
738    #[test]
739    #[cfg(feature = "embed")]
740    fn test_dyn_constant() {
741        let class = ClassBuilder::new("Foo")
742            .dyn_constant("bar", &42, &["Doc 1"], ConstantFlags::Public)
743            .expect("Failed to create constant");
744        assert_eq!(class.constants.len(), 1);
745        assert_eq!(class.constants[0].0, "bar");
746        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
747    }
748
749    #[test]
750    fn test_flags() {
751        let class = ClassBuilder::new("Foo").flags(ClassFlags::Abstract);
752        assert_eq!(class.ce.ce_flags, ClassFlags::Abstract.bits());
753    }
754
755    #[test]
756    fn test_registration() {
757        let class = ClassBuilder::new("Foo").registration(|_, _| {});
758        assert!(class.register.is_some());
759    }
760
761    #[test]
762    fn test_registration_interface() {
763        let class = ClassBuilder::new("Foo")
764            .flags(ClassFlags::Interface)
765            .registration(|_, _| {});
766        assert!(class.register.is_some());
767    }
768
769    #[test]
770    fn test_docs() {
771        let class = ClassBuilder::new("Foo").docs(&["Doc 1"]);
772        assert_eq!(class.docs, &["Doc 1"] as DocComments);
773    }
774
775    // TODO: Test the register function
776}