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_TYPE_NAME_BIT, _ZEND_TYPE_NULLABLE_BIT, IS_DOUBLE, IS_LONG, IS_UNDEF, MAY_BE_ANY,
18 ZEND_INTERNAL_FUNCTION, zend_declare_class_constant_ex, zend_declare_property,
19 zend_declare_typed_property, zend_do_implement_interface, zend_hash_str_find_ptr_lc,
20 zend_register_internal_class_ex, zend_register_internal_interface,
21 },
22 flags::{ClassFlags, ConstantFlags, DataType, MethodFlags, PropertyFlags},
23 types::{ZendClassObject, ZendObject, ZendStr, Zval},
24 zend::function::{SensitiveParameters, mark_sensitive},
25 zend::{ClassEntry, CompilerGlobals, ExecuteData, ExecutorGlobals, FunctionEntry, ZendType},
26 zend_fastcall,
27};
28
29type ConstantEntry = (
31 String,
32 Box<dyn FnOnce() -> Result<Zval>>,
33 DocComments,
34 String,
35 ConstantFlags,
36);
37type PropertyDefault = Option<Box<dyn FnOnce() -> Result<Zval>>>;
38
39pub struct ClassProperty {
41 pub name: String,
43 pub flags: PropertyFlags,
45 pub default: PropertyDefault,
47 pub docs: DocComments,
49 pub ty: Option<DataType>,
51 pub nullable: bool,
53 pub readonly: bool,
55 pub default_stub: Option<String>,
57}
58
59pub(crate) fn first_duplicate<'a>(
63 names: impl IntoIterator<Item = &'a str>,
64 fold_ascii_case: bool,
65) -> Option<&'a str> {
66 let names: Vec<&str> = names.into_iter().collect();
67 names.iter().enumerate().find_map(|(i, name)| {
68 names[..i]
69 .iter()
70 .any(|earlier| {
71 if fold_ascii_case {
72 earlier.eq_ignore_ascii_case(name)
73 } else {
74 earlier == name
75 }
76 })
77 .then_some(*name)
78 })
79}
80
81pub(crate) fn ensure_class_name_free(name: &str) -> Result<()> {
88 let class_table = CompilerGlobals::get().class_table;
89 if class_table.is_null() {
90 return Ok(());
91 }
92 let found = unsafe { zend_hash_str_find_ptr_lc(class_table, name.as_ptr().cast(), name.len()) };
95 if found.is_null() {
96 Ok(())
97 } else {
98 Err(Error::DuplicateClass {
99 class: name.to_owned(),
100 })
101 }
102}
103
104#[must_use]
106pub struct ClassBuilder {
107 pub(crate) name: String,
108 ce: ClassEntry,
109 pub(crate) extends: Option<ClassEntryInfo>,
110 pub(crate) interfaces: Vec<ClassEntryInfo>,
111 pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
112 object_override: Option<unsafe extern "C" fn(class_type: *mut ClassEntry) -> *mut ZendObject>,
113 pub(crate) properties: Vec<ClassProperty>,
114 pub(crate) typed_properties: Vec<ClassProperty>,
117 unless_parent_constructs: Option<FunctionBuilder<'static>>,
121 pub(crate) constants: Vec<ConstantEntry>,
122 register: Option<fn(&'static mut ClassEntry, ArgInfoTables)>,
123 pub(crate) docs: DocComments,
124}
125
126impl ClassBuilder {
127 pub fn new<T: Into<String>>(name: T) -> Self {
134 Self {
135 name: name.into(),
136 ce: unsafe { MaybeUninit::zeroed().assume_init() },
139 extends: None,
140 interfaces: vec![],
141 methods: vec![],
142 object_override: None,
143 properties: vec![],
144 typed_properties: vec![],
145 unless_parent_constructs: None,
146 constants: vec![],
147 register: None,
148 docs: &[],
149 }
150 }
151
152 #[must_use]
154 pub fn get_flags(&self) -> u32 {
155 self.ce.ce_flags
156 }
157
158 pub fn extends(mut self, parent: ClassEntryInfo) -> Self {
164 self.extends = Some(parent);
165 self
166 }
167
168 pub fn implements(mut self, interface: ClassEntryInfo) -> Self {
178 self.interfaces.push(interface);
179 self
180 }
181
182 pub fn method(mut self, func: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
189 self.methods.push((func, flags));
190 self
191 }
192
193 pub fn property(mut self, prop: ClassProperty) -> Self {
199 self.properties.push(prop);
200 self
201 }
202
203 pub fn typed_property(mut self, prop: ClassProperty) -> Self {
227 self.typed_properties.push(prop);
228 self
229 }
230
231 pub fn constant<T: Into<String>>(
248 mut self,
249 name: T,
250 value: impl IntoZval + 'static,
251 docs: DocComments,
252 flags: ConstantFlags,
253 ) -> Result<Self> {
254 let zval = value.into_zval(true)?;
255 let stub = crate::convert::zval_to_stub(&zval);
256 self.constants
257 .push((name.into(), Box::new(|| Ok(zval)), docs, stub, flags));
258 Ok(self)
259 }
260
261 pub fn dyn_constant<T: Into<String>>(
278 mut self,
279 name: T,
280 value: &'static dyn IntoZvalDyn,
281 docs: DocComments,
282 flags: ConstantFlags,
283 ) -> Result<Self> {
284 let stub = value.stub_value();
285 let value = Rc::new(value);
286 self.constants.push((
287 name.into(),
288 Box::new(move || value.as_zval(true)),
289 docs,
290 stub,
291 flags,
292 ));
293 Ok(self)
294 }
295
296 pub fn flags(mut self, flags: ClassFlags) -> Self {
302 self.ce.ce_flags = flags.bits();
303 self
304 }
305
306 pub fn object_override<T: RegisteredClass>(mut self) -> Self {
320 extern "C" fn create_object<T: RegisteredClass>(ce: *mut ClassEntry) -> *mut ZendObject {
321 if let Some(instance) = T::default_init() {
328 let obj = ZendClassObject::<T>::new_in(instance, unsafe { ce.as_ref() }).into_raw();
331 return unsafe { (*obj).get_mut_zend_obj() };
334 }
335
336 let obj = ZendClassObject::<T>::new_uninit(unsafe { ce.as_ref() }).into_raw();
339 unsafe { (*obj).get_mut_zend_obj() }
341 }
342
343 zend_fastcall! {
344 extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
345 crate::zend::run_handler(std::panic::AssertUnwindSafe(|| {
346 let Some(ConstructorMeta { constructor, .. }) = T::constructor() else {
347 PhpException::from_message("You cannot instantiate this class from PHP.".into())
348 .throw();
349 return;
350 };
351
352 let this = match constructor(ex) {
353 ConstructorResult::Ok(this) => this,
354 ConstructorResult::Exception(e) => {
355 e.throw();
356 return;
357 }
358 ConstructorResult::ArgError => return,
359 };
360
361 let Some(this_obj) = ex.get_object::<T>() else {
362 PhpException::from_message("Failed to retrieve reference to `this` object.".into())
363 .throw();
364 return;
365 };
366
367 if let Err(err) = this_obj.initialize(this) {
368 PhpException::from(err).throw();
369 }
370 }));
371 }
372 }
373
374 debug_assert_eq!(
375 self.name.as_str(),
376 T::CLASS_NAME,
377 "Class name in builder does not match class name in `impl RegisteredClass`."
378 );
379 self.object_override = Some(create_object::<T>);
380 let is_interface = T::FLAGS.contains(ClassFlags::Interface);
381
382 if let Some(ConstructorMeta {
388 build_fn, flags, ..
389 }) = T::constructor()
390 {
391 let func = if is_interface {
392 FunctionBuilder::new_abstract("__construct")
393 } else {
394 FunctionBuilder::new("__construct", constructor::<T>)
395 };
396 let visibility = flags.unwrap_or(MethodFlags::Public);
397 self.method(build_fn(func), visibility)
398 } else if is_interface {
399 self
400 } else if T::NO_CONSTRUCTOR {
401 self.unless_parent_constructs =
402 Some(FunctionBuilder::new("__construct", constructor::<T>));
403 self
404 } else {
405 let func = FunctionBuilder::new("__construct", constructor::<T>);
407 self.method(func, MethodFlags::Public)
408 }
409 }
410
411 pub fn registration(mut self, register: fn(&'static mut ClassEntry, ArgInfoTables)) -> Self {
430 self.register = Some(register);
431 self
432 }
433
434 pub fn docs(mut self, docs: DocComments) -> Self {
440 self.docs = docs;
441 self
442 }
443
444 fn validate(&self) -> Result<()> {
447 if let Some(name) = first_duplicate(
448 self.properties
449 .iter()
450 .chain(&self.typed_properties)
451 .map(|p| p.name.as_str()),
452 false,
453 ) {
454 return Err(Error::DuplicateProperty {
455 property: format!("{}::${name}", self.name),
456 });
457 }
458 if let Some(name) = first_duplicate(self.methods.iter().map(|(m, _)| m.name.as_str()), true)
459 {
460 return Err(Error::DuplicateMethod {
461 method: format!("{}::{name}", self.name),
462 });
463 }
464 if let Some(name) = first_duplicate(self.constants.iter().map(|c| c.0.as_str()), false) {
465 return Err(Error::DuplicateConstant {
466 constant: format!("{}::{name}", self.name),
467 });
468 }
469 #[cfg(php82)]
470 let readonly_class = self.ce.ce_flags & ClassFlags::ReadonlyClass.bits() != 0;
471 #[cfg(not(php82))]
472 let readonly_class = false;
473 for prop in &self.typed_properties {
474 let typed = prop
475 .ty
476 .and_then(|ty| property_type_mask(ty, prop.nullable))
477 .is_some();
478 if !typed || prop.readonly || readonly_class {
479 return Err(Error::InvalidPropertyType {
480 property: format!("{}::${}", self.name, prop.name),
481 });
482 }
483 }
484 Ok(())
485 }
486
487 fn keep_throwing_constructor(&mut self) {
491 if let Some(constructor) = self.unless_parent_constructs.take()
492 && self
493 .extends
494 .as_ref()
495 .is_some_and(|(parent, _)| constructs_in_this_module(parent()))
496 {
497 self.methods.push((constructor, MethodFlags::Public));
498 }
499 }
500
501 pub fn register(mut self) -> Result<()> {
521 assert!(
522 !ExecutorGlobals::get().current_module.is_null(),
523 "Classes can only be registered from a module startup (MINIT) function: \
524 `do_register_internal_class` dereferences `EG(current_module)`."
525 );
526 self.validate()?;
527 ensure_class_name_free(&self.name)?;
528
529 self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();
530
531 self.keep_throwing_constructor();
532
533 let mut arg_info = Vec::with_capacity(self.methods.len());
534 let mut methods = Vec::with_capacity(self.methods.len() + 1);
535 let mut sensitive = SensitiveParameters::new();
536 for (method, flags) in self.methods {
537 sensitive.extend(method.sensitive());
538 let (mut entry, args) = method.build()?;
539 entry.add_flags(flags);
540 methods.push(entry);
541 arg_info.push(args);
542 }
543
544 let arg_info = ManuallyDrop::new(arg_info.into_boxed_slice());
551
552 methods.push(FunctionEntry::end());
553 let entries = Box::into_raw(methods.into_boxed_slice());
554 self.ce.info.internal.builtin_functions = entries.cast::<FunctionEntry>().cast_const();
555
556 let class = if self.ce.flags().contains(ClassFlags::Interface) {
557 unsafe { zend_register_internal_interface(&raw mut self.ce) }
558 } else {
559 let parent = match self.extends {
563 Some((ptr, _)) => ptr::from_ref(ptr()).cast_mut(),
564 None => std::ptr::null_mut(),
565 };
566 unsafe { zend_register_internal_class_ex(&raw mut self.ce, parent) }
567 };
568
569 unsafe { free_registered_entries(entries) };
572
573 let class = unsafe { class.as_mut() }.ok_or(Error::InvalidPointer)?;
574 class.info.internal.builtin_functions = ptr::null();
575 mark_sensitive(&raw const class.function_table, &sensitive);
576
577 if self.object_override.is_some() {
579 cfg_if::cfg_if! {
580 if #[cfg(php81)] {
581 class.ce_flags |= ClassFlags::NotSerializable.bits();
582 } else {
583 class.serialize = Some(crate::ffi::zend_class_serialize_deny);
584 class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
585 }
586 }
587 }
588
589 for (iface, _) in self.interfaces {
590 let interface = iface();
591 assert!(
592 interface.is_interface(),
593 "Given class entry was not an interface."
594 );
595
596 unsafe { zend_do_implement_interface(class, ptr::from_ref(interface).cast_mut()) };
597 }
598
599 for prop in self.properties {
600 let mut default_zval = match prop.default {
601 Some(f) => f()?,
602 None => Zval::new(),
603 };
604 unsafe {
605 zend_declare_property(
606 class,
607 CString::new(prop.name.as_str())?.as_ptr(),
608 prop.name.len() as _,
609 &raw mut default_zval,
610 prop.flags.bits().try_into()?,
611 );
612 }
613 }
614
615 for prop in self.typed_properties {
616 declare_typed_property(class, &self.name, prop)?;
617 }
618
619 for (name, value, _, _, flags) in self.constants {
620 let name = ZendStr::new_interned(&name, true);
623 let mut value = ManuallyDrop::new(value()?);
628 unsafe {
629 zend_declare_class_constant_ex(
630 class,
631 name.as_ptr().cast_mut(),
632 &raw mut *value,
633 flags.bits().try_into()?,
634 ptr::null_mut(),
635 );
636 };
637 }
638
639 if let Some(object_override) = self.object_override {
640 class.__bindgen_anon_2.create_object = Some(object_override);
641 }
642
643 if let Some(register) = self.register {
644 register(class, ManuallyDrop::into_inner(arg_info));
645 } else {
646 panic!("Class {} was not registered.", self.name);
647 }
648
649 Ok(())
650 }
651}
652
653pub(crate) fn property_type_mask(ty: DataType, nullable: bool) -> Option<u32> {
664 let nullable = if nullable { _ZEND_TYPE_NULLABLE_BIT } else { 0 };
665 let mask = match ty {
666 DataType::Mixed => return Some(MAY_BE_ANY),
667 DataType::Object(_) if ty.class_name().is_some() => _ZEND_TYPE_NAME_BIT,
668 _ => ZendType::scalar_type_mask(ty)?,
669 };
670 Some(mask | nullable)
671}
672
673#[derive(Debug, PartialEq, Eq)]
676pub(crate) enum DefaultFit {
677 Fits,
679 ToDouble,
681 Refused,
683}
684
685pub(crate) fn default_fit(mask: u32, code: u32) -> DefaultFit {
686 if code == IS_UNDEF || (code < 32 && mask & (1 << code) != 0) {
687 DefaultFit::Fits
688 } else if mask & (1 << IS_DOUBLE) != 0 && code == IS_LONG {
689 DefaultFit::ToDouble
690 } else {
691 DefaultFit::Refused
692 }
693}
694
695fn declare_typed_property(
698 class: &mut ClassEntry,
699 class_name: &str,
700 prop: ClassProperty,
701) -> Result<()> {
702 let invalid = || Error::InvalidPropertyType {
703 property: format!("{class_name}::${}", prop.name),
704 };
705 let ty = prop.ty.ok_or_else(invalid)?;
706 let mask = property_type_mask(ty, prop.nullable).ok_or_else(invalid)?;
707 let type_ptr = match ty.class_name() {
710 Some(name) => ManuallyDrop::new(ZendStr::new_interned(name, true))
711 .as_ptr()
712 .cast_mut()
713 .cast(),
714 None => ptr::null_mut(),
715 };
716 let mut default = if let Some(f) = prop.default {
717 f()?
718 } else {
719 let mut undef = Zval::new();
721 undef.u1.type_info = IS_UNDEF;
722 undef
723 };
724 let code = unsafe { default.u1.type_info } & 0xff;
727 match default_fit(mask, code) {
728 DefaultFit::Fits => {}
729 DefaultFit::ToDouble => {
730 let long = default.long().ok_or_else(invalid)?;
731 #[expect(
732 clippy::cast_precision_loss,
733 reason = "PHP converts an int default to float the same way"
734 )]
735 default.set_double(long as f64);
736 }
737 DefaultFit::Refused => return Err(invalid()),
738 }
739 let name = ZendStr::new_interned(&prop.name, true);
740 unsafe {
743 zend_declare_typed_property(
744 class,
745 name.as_ptr().cast_mut(),
746 &raw mut default,
747 prop.flags.bits().try_into()?,
748 ptr::null_mut(),
749 ZendType {
750 ptr: type_ptr,
751 type_mask: mask,
752 },
753 );
754 }
755 std::mem::forget(default);
756 Ok(())
757}
758
759fn constructs_in_this_module(class: &ClassEntry) -> bool {
763 unsafe { class.constructor.as_ref() }.is_some_and(|constructor| unsafe {
767 u32::from(constructor.type_) == ZEND_INTERNAL_FUNCTION
768 && constructor.internal_function.module == ExecutorGlobals::get().current_module
769 })
770}
771
772#[cfg(test)]
773mod tests {
774 use crate::ffi::{IS_ARRAY, IS_FALSE, IS_NULL, IS_OBJECT, IS_STRING, IS_TRUE, MAY_BE_BOOL};
775 use crate::test::test_function;
776
777 use super::*;
778
779 fn typed(name: &str, ty: DataType, nullable: bool) -> ClassProperty {
780 ClassProperty {
781 name: name.into(),
782 flags: PropertyFlags::Public,
783 default: None,
784 docs: &[],
785 ty: Some(ty),
786 nullable,
787 readonly: false,
788 default_stub: None,
789 }
790 }
791
792 #[test]
793 fn property_type_mask_covers_every_data_type() {
794 let null = _ZEND_TYPE_NULLABLE_BIT;
795 let cases = [
796 (DataType::Undef, None),
797 (DataType::Null, None),
798 (DataType::False, None),
799 (DataType::True, None),
800 (DataType::Long, Some(1 << IS_LONG)),
801 (DataType::Double, Some(1 << IS_DOUBLE)),
802 (DataType::String, Some(1 << IS_STRING)),
803 (DataType::Array, Some(1 << IS_ARRAY)),
804 (DataType::Iterable, None),
805 (DataType::Object("".into()), Some(1 << IS_OBJECT)),
806 (DataType::Object("Foo".into()), Some(_ZEND_TYPE_NAME_BIT)),
807 (DataType::Resource, None),
808 (DataType::Reference, None),
809 (DataType::Callable, None),
810 (DataType::ConstantExpression, None),
811 (DataType::Indirect, None),
812 (DataType::Void, None),
813 (DataType::Mixed, Some(MAY_BE_ANY)),
814 (DataType::Bool, Some(MAY_BE_BOOL)),
815 (DataType::Ptr, None),
816 ];
817 for (ty, mask) in cases {
818 assert_eq!(property_type_mask(ty, false), mask, "{ty:?}");
819 let nullable = match ty {
820 DataType::Mixed => mask,
821 _ => mask.map(|m| m | null),
822 };
823 assert_eq!(property_type_mask(ty, true), nullable, "?{ty:?}");
824 }
825 }
826
827 #[test]
828 fn validate_refuses_a_typed_property_without_a_property_type() {
829 for ty in [
833 DataType::Iterable,
834 DataType::Resource,
835 DataType::ConstantExpression,
836 DataType::Indirect,
837 DataType::Callable,
838 DataType::Void,
839 ] {
840 let class = ClassBuilder::new("Foo").typed_property(typed("a", ty, false));
841 assert!(
842 matches!(
843 class.validate(),
844 Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
845 ),
846 "{ty:?}"
847 );
848 }
849 let mut missing = typed("a", DataType::Long, false);
850 missing.ty = None;
851 assert!(
852 ClassBuilder::new("Foo")
853 .typed_property(missing)
854 .validate()
855 .is_err()
856 );
857 }
858
859 #[test]
860 fn validate_accepts_property_types() {
861 let class = ClassBuilder::new("Foo")
862 .typed_property(typed("a", DataType::Long, false))
863 .typed_property(typed("b", DataType::String, true))
864 .typed_property(typed("c", DataType::Object("ArrayObject".into()), false))
865 .typed_property(typed("d", DataType::Mixed, true))
866 .property(typed("e", DataType::Iterable, false));
868 assert!(class.validate().is_ok());
869 }
870
871 #[test]
872 fn default_fit_as_zend_is_valid_default_value() {
873 let mask = |ty, nullable| property_type_mask(ty, nullable).expect("a property type");
874 let float = mask(DataType::Double, false);
875 assert_eq!(default_fit(float, IS_LONG), DefaultFit::ToDouble);
876 assert_eq!(default_fit(float, IS_DOUBLE), DefaultFit::Fits);
877 let string = mask(DataType::String, false);
878 assert_eq!(default_fit(string, IS_LONG), DefaultFit::Refused);
879 let int = mask(DataType::Long, false);
880 assert_eq!(default_fit(int, IS_DOUBLE), DefaultFit::Refused);
881 assert_eq!(default_fit(int, IS_NULL), DefaultFit::Refused);
882 assert_eq!(default_fit(int, IS_UNDEF), DefaultFit::Fits);
883 let nullable_int = mask(DataType::Long, true);
884 assert_eq!(default_fit(nullable_int, IS_NULL), DefaultFit::Fits);
885 let class = mask(DataType::Object("Foo".into()), false);
886 assert_eq!(default_fit(class, IS_LONG), DefaultFit::Refused);
887 assert_eq!(default_fit(class, IS_OBJECT), DefaultFit::Refused);
888 let boolean = mask(DataType::Bool, false);
889 assert_eq!(default_fit(boolean, IS_TRUE), DefaultFit::Fits);
890 assert_eq!(default_fit(boolean, IS_FALSE), DefaultFit::Fits);
891 }
892
893 #[test]
894 fn validate_refuses_readonly_typed_properties() {
895 let mut readonly = typed("a", DataType::Long, false);
896 readonly.readonly = true;
897 assert!(matches!(
898 ClassBuilder::new("Foo").typed_property(readonly).validate(),
899 Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
900 ));
901 }
902
903 #[test]
904 #[cfg(php82)]
905 fn validate_refuses_typed_properties_on_a_readonly_class() {
906 let class = ClassBuilder::new("Foo")
909 .flags(ClassFlags::ReadonlyClass)
910 .typed_property(typed("a", DataType::Long, false));
911 assert!(matches!(
912 class.validate(),
913 Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
914 ));
915 }
916
917 #[test]
918 fn validate_refuses_a_typed_property_repeating_an_untyped_one() {
919 let class = ClassBuilder::new("Foo")
920 .property(typed("a", DataType::Long, false))
921 .typed_property(typed("a", DataType::Long, false));
922 assert!(matches!(
923 class.validate(),
924 Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
925 ));
926 }
927
928 #[test]
929 #[allow(unpredictable_function_pointer_comparisons)]
930 fn test_new() {
931 let class = ClassBuilder::new("Foo");
932 assert_eq!(class.name, "Foo");
933 assert_eq!(class.extends, None);
934 assert_eq!(class.interfaces, vec![]);
935 assert_eq!(class.methods.len(), 0);
936 assert_eq!(class.object_override, None);
937 assert!(class.properties.is_empty());
938 assert_eq!(class.constants.len(), 0);
939 assert_eq!(class.register, None);
940 assert_eq!(class.docs, &[] as DocComments);
941 }
942
943 #[test]
944 fn test_extends() {
945 let extends: ClassEntryInfo = (|| todo!(), "Bar");
946 let class = ClassBuilder::new("Foo").extends(extends);
947 assert_eq!(class.extends, Some(extends));
948 }
949
950 #[test]
951 fn test_implements() {
952 let implements: ClassEntryInfo = (|| todo!(), "Bar");
953 let class = ClassBuilder::new("Foo").implements(implements);
954 assert_eq!(class.interfaces, vec![implements]);
955 }
956
957 #[test]
958 fn test_method() {
959 let method = FunctionBuilder::new("foo", test_function);
960 let class = ClassBuilder::new("Foo").method(method, MethodFlags::Public);
961 assert_eq!(class.methods.len(), 1);
962 }
963
964 #[test]
965 fn test_property() {
966 let class = ClassBuilder::new("Foo").property(ClassProperty {
967 name: "bar".into(),
968 flags: PropertyFlags::Public,
969 default: None,
970 docs: &["Doc 1"],
971 ty: Some(DataType::String),
972 nullable: false,
973 readonly: false,
974 default_stub: None,
975 });
976 assert_eq!(class.properties.len(), 1);
977 assert_eq!(class.properties[0].name, "bar");
978 assert_eq!(class.properties[0].flags, PropertyFlags::Public);
979 assert!(class.properties[0].default.is_none());
980 assert_eq!(class.properties[0].docs, &["Doc 1"] as DocComments);
981 assert_eq!(class.properties[0].ty, Some(DataType::String));
982 }
983
984 fn named_property(name: &str) -> ClassProperty {
985 ClassProperty {
986 name: name.into(),
987 flags: PropertyFlags::Public,
988 default: None,
989 docs: &[],
990 ty: None,
991 nullable: false,
992 readonly: false,
993 default_stub: None,
994 }
995 }
996
997 fn with_constant(mut class: ClassBuilder, name: &str) -> ClassBuilder {
998 class.constants.push((
999 name.into(),
1000 Box::new(|| Err(Error::InvalidPointer)),
1001 &[],
1002 String::new(),
1003 ConstantFlags::Public,
1004 ));
1005 class
1006 }
1007
1008 #[test]
1009 fn first_duplicate_folds_ascii_case_only_when_asked() {
1010 assert_eq!(first_duplicate(["a", "b", "a"], false), Some("a"));
1011 assert_eq!(first_duplicate(["a", "B", "b"], false), None);
1012 assert_eq!(first_duplicate(["a", "B", "b"], true), Some("b"));
1013 assert_eq!(first_duplicate(["ä", "Ä"], true), None);
1014 assert_eq!(first_duplicate([], true), None);
1015 }
1016
1017 #[test]
1018 fn validate_rejects_a_repeated_property() {
1019 let mut class = ClassBuilder::new("Foo");
1020 class.properties = vec![named_property("a"), named_property("a")];
1021 assert!(matches!(
1022 class.validate(),
1023 Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
1024 ));
1025 }
1026
1027 #[test]
1028 fn validate_rejects_methods_that_differ_only_by_case() {
1029 let class = ClassBuilder::new("Foo")
1030 .method(
1031 FunctionBuilder::new("run", test_function),
1032 MethodFlags::Public,
1033 )
1034 .method(
1035 FunctionBuilder::new("RUN", test_function),
1036 MethodFlags::Static,
1037 );
1038 assert!(matches!(
1039 class.validate(),
1040 Err(Error::DuplicateMethod { method }) if method == "Foo::RUN"
1041 ));
1042 }
1043
1044 #[test]
1045 fn validate_compares_constants_exactly() {
1046 let class = with_constant(with_constant(ClassBuilder::new("Foo"), "A"), "a");
1047 assert!(class.validate().is_ok());
1048 let class = with_constant(class, "A");
1049 assert!(matches!(
1050 class.validate(),
1051 Err(Error::DuplicateConstant { constant }) if constant == "Foo::A"
1052 ));
1053 }
1054
1055 #[test]
1056 #[cfg(feature = "embed")]
1057 fn class_names_already_in_the_class_table_are_taken() {
1058 let ran = crate::embed::Embed::run(|| {
1059 assert!(matches!(
1060 ensure_class_name_free("STDCLASS"),
1061 Err(Error::DuplicateClass { class }) if class == "STDCLASS"
1062 ));
1063 assert!(ensure_class_name_free("ExtPhpRsNoSuchClass").is_ok());
1064 true
1065 });
1066 assert!(ran);
1067 }
1068
1069 #[test]
1070 fn validate_accepts_distinct_members() {
1071 let mut class = ClassBuilder::new("Foo")
1072 .method(
1073 FunctionBuilder::new("run", test_function),
1074 MethodFlags::Public,
1075 )
1076 .method(
1077 FunctionBuilder::new("stop", test_function),
1078 MethodFlags::Public,
1079 );
1080 class.properties = vec![named_property("a"), named_property("b")];
1081 assert!(with_constant(class, "A").validate().is_ok());
1082 }
1083
1084 #[test]
1085 #[cfg(feature = "embed")]
1086 fn test_constant() {
1087 let class = ClassBuilder::new("Foo")
1088 .constant("bar", 42, &["Doc 1"], ConstantFlags::Public)
1089 .expect("Failed to create constant");
1090 assert_eq!(class.constants.len(), 1);
1091 assert_eq!(class.constants[0].0, "bar");
1092 assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
1093 }
1094
1095 #[test]
1096 #[cfg(feature = "embed")]
1097 fn test_dyn_constant() {
1098 let class = ClassBuilder::new("Foo")
1099 .dyn_constant("bar", &42, &["Doc 1"], ConstantFlags::Public)
1100 .expect("Failed to create constant");
1101 assert_eq!(class.constants.len(), 1);
1102 assert_eq!(class.constants[0].0, "bar");
1103 assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
1104 }
1105
1106 #[test]
1107 fn test_flags() {
1108 let class = ClassBuilder::new("Foo").flags(ClassFlags::Abstract);
1109 assert_eq!(class.ce.ce_flags, ClassFlags::Abstract.bits());
1110 }
1111
1112 #[test]
1113 fn test_registration() {
1114 let class = ClassBuilder::new("Foo").registration(|_, _| {});
1115 assert!(class.register.is_some());
1116 }
1117
1118 #[test]
1119 fn test_registration_interface() {
1120 let class = ClassBuilder::new("Foo")
1121 .flags(ClassFlags::Interface)
1122 .registration(|_, _| {});
1123 assert!(class.register.is_some());
1124 }
1125
1126 #[test]
1127 fn test_docs() {
1128 let class = ClassBuilder::new("Foo").docs(&["Doc 1"]);
1129 assert_eq!(class.docs, &["Doc 1"] as DocComments);
1130 }
1131
1132 }