• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

davidcole1340 / ext-php-rs / 16398853116

20 Jul 2025 10:21AM UTC coverage: 26.874% (+1.1%) from 25.766%
16398853116

Pull #489

github

Xenira
test(enum): add enum testcases

Refs: #178
Pull Request #489: feat(enum): add basic enum support

118 of 299 new or added lines in 8 files covered. (39.46%)

1 existing line in 1 file now uncovered.

1115 of 4149 relevant lines covered (26.87%)

5.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

30.43
/src/builders/enum_builder.rs
1
use std::{ffi::CString, ptr};
2

3
use crate::{
4
    builders::FunctionBuilder,
5
    convert::IntoZval,
6
    describe::DocComments,
7
    enum_::EnumCase,
8
    error::Result,
9
    ffi::{zend_enum_add_case, zend_register_internal_enum},
10
    flags::{DataType, MethodFlags},
11
    types::{ZendStr, Zval},
12
    zend::{ClassEntry, FunctionEntry},
13
};
14

15
/// A builder for PHP enums.
16
#[must_use]
17
pub struct EnumBuilder {
18
    pub(crate) name: String,
19
    pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
20
    pub(crate) cases: Vec<&'static EnumCase>,
21
    pub(crate) datatype: DataType,
22
    register: Option<fn(&'static mut ClassEntry)>,
23
    pub(crate) docs: DocComments,
24
}
25

26
impl EnumBuilder {
27
    /// Creates a new enum builder with the given name.
28
    pub fn new<T: Into<String>>(name: T) -> Self {
6✔
29
        Self {
30
            name: name.into(),
18✔
31
            methods: Vec::default(),
12✔
32
            cases: Vec::default(),
12✔
33
            datatype: DataType::Undef,
34
            register: None,
35
            docs: DocComments::default(),
6✔
36
        }
37
    }
38

39
    /// Adds an enum case to the enum.
40
    ///
41
    /// # Panics
42
    ///
43
    /// If the case's data type does not match the enum's data type
44
    pub fn case(mut self, case: &'static EnumCase) -> Self {
5✔
45
        let data_type = case.data_type();
15✔
46
        assert!(
5✔
47
            data_type == self.datatype || self.cases.is_empty(),
8✔
48
            "Cannot add case with data type {:?} to enum with data type {:?}",
1✔
49
            data_type,
50
            self.datatype
51
        );
52

53
        self.datatype = data_type;
4✔
54
        self.cases.push(case);
55

56
        self
57
    }
58

59
    /// Adds a method to the enum.
NEW
60
    pub fn method(mut self, method: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
×
NEW
61
        self.methods.push((method, flags));
×
NEW
62
        self
×
63
    }
64

65
    /// Function to register the class with PHP. This function is called after
66
    /// the class is built.
67
    ///
68
    /// # Parameters
69
    ///
70
    /// * `register` - The function to call to register the class.
NEW
71
    pub fn registration(mut self, register: fn(&'static mut ClassEntry)) -> Self {
×
NEW
72
        self.register = Some(register);
×
NEW
73
        self
×
74
    }
75

76
    /// Add documentation comments to the enum.
77
    pub fn docs(mut self, docs: DocComments) -> Self {
1✔
78
        self.docs = docs;
1✔
79
        self
1✔
80
    }
81

82
    /// Registers the enum with PHP.
83
    ///
84
    /// # Panics
85
    ///
86
    /// If the registration function was not set prior to calling this
87
    /// method.
88
    ///
89
    /// # Errors
90
    ///
91
    /// If the enum could not be registered, e.g. due to an invalid name or
92
    /// data type.
NEW
93
    pub fn register(self) -> Result<()> {
×
NEW
94
        let mut methods = self
×
NEW
95
            .methods
×
96
            .into_iter()
NEW
97
            .map(|(method, flags)| {
×
NEW
98
                method.build().map(|mut method| {
×
NEW
99
                    method.flags |= flags.bits();
×
NEW
100
                    method
×
101
                })
102
            })
103
            .collect::<Result<Vec<_>>>()?;
NEW
104
        methods.push(FunctionEntry::end());
×
105

106
        let class = unsafe {
107
            zend_register_internal_enum(
NEW
108
                CString::new(self.name)?.as_ptr(),
×
NEW
109
                self.datatype.as_u32().try_into()?,
×
NEW
110
                methods.into_boxed_slice().as_ptr(),
×
111
            )
112
        };
113

NEW
114
        for case in self.cases {
×
NEW
115
            let name = ZendStr::new_interned(case.name, true);
×
NEW
116
            let value = match &case.discriminant {
×
NEW
117
                Some(value) => {
×
NEW
118
                    let value: Zval = match value {
×
NEW
119
                        crate::enum_::Discriminant::Int(i) => i.into_zval(false)?,
×
NEW
120
                        crate::enum_::Discriminant::String(s) => s.into_zval(true)?,
×
121
                    };
NEW
122
                    let mut zv = core::mem::ManuallyDrop::new(value);
×
NEW
123
                    (&raw mut zv).cast()
×
124
                }
NEW
125
                None => ptr::null_mut(),
×
126
            };
127
            unsafe {
NEW
128
                zend_enum_add_case(class, name.into_raw(), value);
×
129
            }
130
        }
131

NEW
132
        if let Some(register) = self.register {
×
NEW
133
            register(unsafe { &mut *class });
×
134
        } else {
NEW
135
            panic!("Enum was not registered with a registration function",);
×
136
        }
137

NEW
138
        Ok(())
×
139
    }
140
}
141

142
#[cfg(test)]
143
mod tests {
144
    use super::*;
145
    use crate::enum_::Discriminant;
146

147
    const case1: EnumCase = EnumCase {
148
        name: "Variant1",
149
        discriminant: None,
150
        docs: &[],
151
    };
152
    const case2: EnumCase = EnumCase {
153
        name: "Variant2",
154
        discriminant: Some(Discriminant::Int(42)),
155
        docs: &[],
156
    };
157
    const case3: EnumCase = EnumCase {
158
        name: "Variant3",
159
        discriminant: Some(Discriminant::String("foo")),
160
        docs: &[],
161
    };
162

163
    #[test]
164
    fn test_new_enum_builder() {
165
        let builder = EnumBuilder::new("MyEnum");
166
        assert_eq!(builder.name, "MyEnum");
167
        assert!(builder.methods.is_empty());
168
        assert!(builder.cases.is_empty());
169
        assert_eq!(builder.datatype, DataType::Undef);
170
        assert!(builder.register.is_none());
171
    }
172

173
    #[test]
174
    fn test_enum_case() {
175
        let builder = EnumBuilder::new("MyEnum").case(&case1);
176
        assert_eq!(builder.cases.len(), 1);
177
        assert_eq!(builder.cases[0].name, "Variant1");
178
        assert_eq!(builder.datatype, DataType::Undef);
179

180
        let builder = EnumBuilder::new("MyEnum").case(&case2);
181
        assert_eq!(builder.cases.len(), 1);
182
        assert_eq!(builder.cases[0].name, "Variant2");
183
        assert_eq!(builder.cases[0].discriminant, Some(Discriminant::Int(42)));
184
        assert_eq!(builder.datatype, DataType::Long);
185

186
        let builder = EnumBuilder::new("MyEnum").case(&case3);
187
        assert_eq!(builder.cases.len(), 1);
188
        assert_eq!(builder.cases[0].name, "Variant3");
189
        assert_eq!(
190
            builder.cases[0].discriminant,
191
            Some(Discriminant::String("foo"))
192
        );
193
        assert_eq!(builder.datatype, DataType::String);
194
    }
195

196
    #[test]
197
    #[should_panic(expected = "Cannot add case with data type Long to enum with data type Undef")]
198
    fn test_enum_case_mismatch() {
199
        #[allow(unused_must_use)]
200
        EnumBuilder::new("MyEnum").case(&case1).case(&case2); // This should panic because case2 has a different data type
201
    }
202

203
    const docs: DocComments = &["This is a test enum"];
204
    #[test]
205
    fn test_docs() {
206
        let builder = EnumBuilder::new("MyEnum").docs(docs);
207
        assert_eq!(builder.docs.len(), 1);
208
        assert_eq!(builder.docs[0], "This is a test enum");
209
    }
210
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc