aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-symfony-console/src/input/input_option.rs
blob: d37e18aef42bdcf1b6abf7f81ef46eb49f5e399d (plain)
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
//! ref: composer/vendor/symfony/console/Input/InputOption.php

use crate::exception::InvalidArgumentException;
use crate::exception::LogicException;
use shirabe_php_shim::{PhpMixed, php_regex, preg_split};

#[derive(Debug, Clone)]
pub struct InputOption {
    name: String,
    shortcut: Option<String>,
    mode: i64,
    default: PhpMixed,
    description: String,
}

impl InputOption {
    pub const VALUE_NONE: i64 = 1;
    pub const VALUE_REQUIRED: i64 = 2;
    pub const VALUE_OPTIONAL: i64 = 4;
    pub const VALUE_IS_ARRAY: i64 = 8;
    pub const VALUE_NEGATABLE: i64 = 16;

    pub fn new(
        name: &str,
        shortcut: PhpMixed,
        mode: Option<i64>,
        description: String,
        default: PhpMixed,
    ) -> anyhow::Result<Self> {
        let name = if let Some(stripped) = name.strip_prefix("--") {
            stripped.to_string()
        } else {
            name.to_string()
        };

        if name.is_empty() {
            return Err(InvalidArgumentException::new(
                "An option name cannot be empty.".to_string(),
            )
            .into());
        }

        let shortcut = match shortcut {
            PhpMixed::String(ref s) if s.is_empty() => None,
            PhpMixed::List(ref v) if v.is_empty() => None,
            PhpMixed::Bool(false) => None,
            PhpMixed::Null => None,
            PhpMixed::List(ref arr) => {
                let parts: Vec<String> = arr
                    .iter()
                    .filter_map(|v| {
                        if let PhpMixed::String(s) = v {
                            Some(s.clone())
                        } else {
                            None
                        }
                    })
                    .collect();
                let joined = shirabe_php_shim::implode("|", &parts);
                Self::normalize_shortcut(joined)?
            }
            PhpMixed::String(s) => Self::normalize_shortcut(s)?,
            _ => None,
        };

        let mode = match mode {
            None => Self::VALUE_NONE,
            Some(m) if !(1..(Self::VALUE_NEGATABLE << 1)).contains(&m) => {
                return Err(InvalidArgumentException::new(format!(
                    "Option mode \"{}\" is not valid.",
                    m
                ))
                .into());
            }
            Some(m) => m,
        };

        let mut option = InputOption {
            name,
            shortcut,
            mode,
            description,
            default: PhpMixed::Null,
        };

        if option.is_array() && !option.accept_value() {
            return Err(InvalidArgumentException::new("Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.".to_string())
            .into());
        }
        if option.is_negatable() && option.accept_value() {
            return Err(InvalidArgumentException::new("Impossible to have an option mode VALUE_NEGATABLE if the option also accepts a value.".to_string())
            .into());
        }

        option.set_default(default)?;

        Ok(option)
    }

    fn normalize_shortcut(s: String) -> anyhow::Result<Option<String>> {
        let stripped = shirabe_php_shim::ltrim(&s, Some("-"));
        let parts = preg_split(php_regex!(r"{(\|)-?}"), &stripped);
        let filtered: Vec<String> =
            shirabe_php_shim::array_filter(&parts, |s: &String| !s.is_empty());
        let result = shirabe_php_shim::implode("|", &filtered);
        if result.is_empty() {
            return Err(InvalidArgumentException::new(
                "An option shortcut cannot be empty.".to_string(),
            )
            .into());
        }
        Ok(Some(result))
    }

    pub fn get_shortcut(&self) -> Option<&str> {
        self.shortcut.as_deref()
    }

    pub fn get_name(&self) -> &str {
        &self.name
    }

    pub fn accept_value(&self) -> bool {
        self.is_value_required() || self.is_value_optional()
    }

    pub fn is_value_required(&self) -> bool {
        Self::VALUE_REQUIRED == (Self::VALUE_REQUIRED & self.mode)
    }

    pub fn is_value_optional(&self) -> bool {
        Self::VALUE_OPTIONAL == (Self::VALUE_OPTIONAL & self.mode)
    }

    pub fn is_array(&self) -> bool {
        Self::VALUE_IS_ARRAY == (Self::VALUE_IS_ARRAY & self.mode)
    }

    pub fn is_negatable(&self) -> bool {
        Self::VALUE_NEGATABLE == (Self::VALUE_NEGATABLE & self.mode)
    }

    pub fn set_default(&mut self, default: PhpMixed) -> anyhow::Result<()> {
        if Self::VALUE_NONE == (Self::VALUE_NONE & self.mode) && !matches!(default, PhpMixed::Null)
        {
            return Err(LogicException::new(
                "Cannot set a default value when using InputOption::VALUE_NONE mode.".to_string(),
            )
            .into());
        }

        let default = if self.is_array() {
            match default {
                PhpMixed::Null => PhpMixed::List(vec![]),
                // PHP `is_array()` accepts both list-style and associative arrays.
                PhpMixed::List(_) | PhpMixed::Array(_) => default,
                _ => {
                    return Err(LogicException::new(
                        "A default value for an array option must be an array.".to_string(),
                    )
                    .into());
                }
            }
        } else {
            default
        };

        self.default = if self.accept_value() || self.is_negatable() {
            default
        } else {
            PhpMixed::Bool(false)
        };
        Ok(())
    }

    pub fn get_default(&self) -> &PhpMixed {
        &self.default
    }

    pub fn get_description(&self) -> &str {
        &self.description
    }

    pub fn equals(&self, option: &InputOption) -> bool {
        option.get_name() == self.get_name()
            && option.get_shortcut() == self.get_shortcut()
            && option.get_default() == self.get_default()
            && option.is_negatable() == self.is_negatable()
            && option.is_array() == self.is_array()
            && option.is_value_required() == self.is_value_required()
            && option.is_value_optional() == self.is_value_optional()
    }
}

/// The `bool|string|string[]|null` domain of a parsed option value, as returned by
/// [`InputInterface::get_option`](crate::input::InputInterface::get_option).
#[derive(Debug, Clone, PartialEq)]
pub enum InputOptionValue {
    Null,
    Bool(bool),
    String(String),
    Array(Vec<String>),
}

impl InputOptionValue {
    /// Narrows a raw option value to this domain.
    ///
    /// TODO(type-model): `Input` keeps parsed options and `InputOption` defaults as `PhpMixed`, so
    /// a value outside this domain — an int, a float, or an array holding one — can only be
    /// rejected here.
    pub(crate) fn from_php_mixed(value: &PhpMixed) -> Self {
        match value {
            PhpMixed::Null => Self::Null,
            PhpMixed::Bool(b) => Self::Bool(*b),
            PhpMixed::String(s) => Self::String(s.clone()),
            PhpMixed::List(_) | PhpMixed::Array(_) => Self::Array(
                value
                    .values()
                    .into_iter()
                    .map(|item| match item {
                        PhpMixed::String(s) => s.clone(),
                        other => panic!("an option array holds {:?}, not a string", other),
                    })
                    .collect(),
            ),
            other => panic!(
                "an option holds {:?}, not a bool, string, array or null",
                other
            ),
        }
    }

    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_string(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&[String]> {
        match self {
            Self::Array(items) => Some(items),
            _ => None,
        }
    }

    /// PHP loose boolean cast `(bool) $value`.
    pub fn to_bool(&self) -> bool {
        match self {
            Self::Null => false,
            Self::Bool(b) => *b,
            Self::String(s) => !s.is_empty() && s != "0",
            Self::Array(items) => !items.is_empty(),
        }
    }
}

impl From<InputOptionValue> for PhpMixed {
    fn from(value: InputOptionValue) -> Self {
        match value {
            InputOptionValue::Null => PhpMixed::Null,
            InputOptionValue::Bool(b) => PhpMixed::Bool(b),
            InputOptionValue::String(s) => PhpMixed::String(s),
            InputOptionValue::Array(items) => {
                PhpMixed::List(items.into_iter().map(PhpMixed::String).collect())
            }
        }
    }
}