php_codegen/
enum_case.rs

1use crate::attribute::AttributeGroup;
2use crate::comment::Document;
3use crate::literal::Value;
4use crate::Generator;
5use crate::Indentation;
6
7#[derive(Debug)]
8pub struct EnumCase {
9    pub documentation: Option<Document>,
10    pub attributes: Vec<AttributeGroup>,
11    pub name: String,
12    pub value: Option<Value>,
13}
14
15impl EnumCase {
16    pub fn new<T: ToString>(name: T) -> Self {
17        Self {
18            documentation: None,
19            attributes: vec![],
20            name: name.to_string(),
21            value: None,
22        }
23    }
24
25    pub fn document(mut self, documentation: Document) -> Self {
26        self.documentation = Some(documentation);
27
28        self
29    }
30
31    pub fn attributes(mut self, attributes: AttributeGroup) -> Self {
32        self.attributes.push(attributes);
33
34        self
35    }
36
37    pub fn valued<T: Into<Value>>(mut self, value: T) -> Self {
38        self.value = Some(value.into());
39
40        self
41    }
42}
43
44impl Generator for EnumCase {
45    fn generate(&self, indentation: Indentation, level: usize) -> String {
46        let mut code = String::new();
47
48        if let Some(document) = &self.documentation {
49            code.push_str(&document.generate(indentation, level));
50        }
51
52        for attribute in &self.attributes {
53            code.push_str(&attribute.generate(indentation, level));
54        }
55
56        code.push_str(&indentation.indent(format!("case {}", self.name), level));
57
58        if let Some(value) = &self.value {
59            code.push_str(&format!(" = {};\n", value.generate(indentation, level)));
60        } else {
61            code.push_str(";\n");
62        }
63
64        code
65    }
66}
67
68impl Generator for Vec<EnumCase> {
69    fn generate(&self, indentation: Indentation, level: usize) -> String {
70        let mut code = String::new();
71        if self.is_empty() {
72            return code;
73        }
74
75        for case in self {
76            code.push_str(case.generate(indentation, level).as_str());
77            code.push('\n');
78        }
79
80        code
81    }
82}
83
84impl<T: ToString, Tv: Into<Value>> From<(T, Tv)> for EnumCase {
85    fn from((name, value): (T, Tv)) -> Self {
86        Self {
87            documentation: None,
88            attributes: vec![],
89            name: name.to_string(),
90            value: Some(value.into()),
91        }
92    }
93}
94
95impl From<String> for EnumCase {
96    fn from(name: String) -> Self {
97        Self {
98            documentation: None,
99            attributes: vec![],
100            name,
101            value: None,
102        }
103    }
104}
105
106impl From<&str> for EnumCase {
107    fn from(name: &str) -> Self {
108        Self {
109            documentation: None,
110            attributes: vec![],
111            name: name.to_string(),
112            value: None,
113        }
114    }
115}