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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
|
//! ref: composer/vendor/symfony/console/Input/InputDefinition.php
use crate::symfony::console::exception::invalid_argument_exception::InvalidArgumentException;
use crate::symfony::console::exception::logic_exception::LogicException;
use crate::symfony::console::input::input_argument::InputArgument;
use crate::symfony::console::input::input_option::InputOption;
use indexmap::IndexMap;
use shirabe_php_shim::PhpMixed;
use std::rc::Rc;
/// A InputDefinition represents a set of valid command line arguments and options.
///
/// `InputArgument` and `InputOption` are stored behind `Rc` to model PHP's
/// shared object references; this also lets the definition be cloned cheaply
/// (PHP `bind` assigns the definition by reference).
#[derive(Debug, Clone)]
pub struct InputDefinition {
arguments: IndexMap<String, Rc<InputArgument>>,
required_count: i64,
last_array_argument: Option<Rc<InputArgument>>,
last_optional_argument: Option<Rc<InputArgument>>,
options: IndexMap<String, Rc<InputOption>>,
negations: IndexMap<String, String>,
shortcuts: IndexMap<String, String>,
}
/// A definition entry is either an InputArgument or an InputOption.
#[derive(Debug)]
pub enum DefinitionItem {
InputArgument(InputArgument),
InputOption(InputOption),
}
impl InputDefinition {
pub fn new(definition: Vec<DefinitionItem>) -> anyhow::Result<Self> {
let mut input_definition = InputDefinition {
arguments: IndexMap::new(),
required_count: 0,
last_array_argument: None,
last_optional_argument: None,
options: IndexMap::new(),
negations: IndexMap::new(),
shortcuts: IndexMap::new(),
};
input_definition.set_definition(definition)?;
Ok(input_definition)
}
/// Sets the definition of the input.
pub fn set_definition(&mut self, definition: Vec<DefinitionItem>) -> anyhow::Result<()> {
let mut arguments = vec![];
let mut options = vec![];
for item in definition {
match item {
DefinitionItem::InputOption(option) => {
options.push(option);
}
DefinitionItem::InputArgument(argument) => {
arguments.push(argument);
}
}
}
self.set_arguments(arguments)?;
self.set_options(options)?;
Ok(())
}
/// Sets the InputArgument objects.
pub fn set_arguments(&mut self, arguments: Vec<InputArgument>) -> anyhow::Result<()> {
self.arguments = IndexMap::new();
self.required_count = 0;
self.last_optional_argument = None;
self.last_array_argument = None;
self.add_arguments(Some(arguments))?;
Ok(())
}
/// Adds an array of InputArgument objects.
pub fn add_arguments(&mut self, arguments: Option<Vec<InputArgument>>) -> anyhow::Result<()> {
if let Some(arguments) = arguments {
for argument in arguments {
self.add_argument(argument)?;
}
}
Ok(())
}
pub fn add_argument(&mut self, argument: InputArgument) -> anyhow::Result<()> {
let argument = Rc::new(argument);
if self.arguments.contains_key(argument.get_name()) {
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"An argument with name \"{}\" already exists.",
PhpMixed::String(argument.get_name().to_string()),
),
code: 0,
})
.into());
}
if let Some(last_array_argument) = &self.last_array_argument {
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"Cannot add a required argument \"{}\" after an array argument \"{}\".",
PhpMixed::String(argument.get_name().to_string()),
PhpMixed::String(last_array_argument.get_name().to_string()),
),
code: 0,
})
.into());
}
if argument.is_required()
&& let Some(last_optional_argument) = &self.last_optional_argument
{
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"Cannot add a required argument \"{}\" after an optional one \"{}\".",
PhpMixed::String(argument.get_name().to_string()),
PhpMixed::String(last_optional_argument.get_name().to_string()),
),
code: 0,
})
.into());
}
if argument.is_array() {
self.last_array_argument = Some(Rc::clone(&argument));
}
if argument.is_required() {
self.required_count += 1;
} else {
self.last_optional_argument = Some(Rc::clone(&argument));
}
self.arguments
.insert(argument.get_name().to_string(), argument);
Ok(())
}
/// Returns an InputArgument by name or by position.
pub fn get_argument(&self, name: &PhpMixed) -> anyhow::Result<Rc<InputArgument>> {
if !self.has_argument(name) {
return Err(
InvalidArgumentException(shirabe_php_shim::InvalidArgumentException {
message: format!("The \"{}\" argument does not exist.", name.clone(),),
code: 0,
})
.into(),
);
}
match name {
PhpMixed::Int(index) => {
let arguments: Vec<Rc<InputArgument>> = self.arguments.values().cloned().collect();
Ok(Rc::clone(&arguments[*index as usize]))
}
_ => {
let key = shirabe_php_shim::php_to_string(name);
Ok(Rc::clone(&self.arguments[&key]))
}
}
}
/// Returns true if an InputArgument object exists by name or position.
pub fn has_argument(&self, name: &PhpMixed) -> bool {
match name {
PhpMixed::Int(index) => {
let arguments: Vec<Rc<InputArgument>> = self.arguments.values().cloned().collect();
*index >= 0 && (*index as usize) < arguments.len()
}
_ => {
let key = shirabe_php_shim::php_to_string(name);
self.arguments.contains_key(&key)
}
}
}
/// Gets the array of InputArgument objects.
pub fn get_arguments(&self) -> &IndexMap<String, Rc<InputArgument>> {
&self.arguments
}
/// Returns the number of InputArguments.
pub fn get_argument_count(&self) -> i64 {
if self.last_array_argument.is_some() {
i64::MAX
} else {
self.arguments.len() as i64
}
}
/// Returns the number of required InputArguments.
pub fn get_argument_required_count(&self) -> i64 {
self.required_count
}
pub fn get_argument_defaults(&self) -> IndexMap<String, PhpMixed> {
let mut values = IndexMap::new();
for argument in self.arguments.values() {
values.insert(
argument.get_name().to_string(),
argument.get_default().clone(),
);
}
values
}
/// Sets the InputOption objects.
pub fn set_options(&mut self, options: Vec<InputOption>) -> anyhow::Result<()> {
self.options = IndexMap::new();
self.shortcuts = IndexMap::new();
self.negations = IndexMap::new();
self.add_options(options)?;
Ok(())
}
/// Adds an array of InputOption objects.
pub fn add_options(&mut self, options: Vec<InputOption>) -> anyhow::Result<()> {
for option in options {
self.add_option(option)?;
}
Ok(())
}
pub fn add_option(&mut self, option: InputOption) -> anyhow::Result<()> {
let option = Rc::new(option);
if let Some(existing) = self.options.get(option.get_name())
&& !option.equals(existing)
{
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"An option named \"{}\" already exists.",
PhpMixed::String(option.get_name().to_string()),
),
code: 0,
})
.into());
}
if self.negations.contains_key(option.get_name()) {
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"An option named \"{}\" already exists.",
PhpMixed::String(option.get_name().to_string()),
),
code: 0,
})
.into());
}
if let Some(shortcut) = option.get_shortcut() {
for shortcut in shirabe_php_shim::explode("|", shortcut) {
if let Some(existing_name) = self.shortcuts.get(&shortcut)
&& !option.equals(&self.options[existing_name])
{
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"An option with shortcut \"{}\" already exists.",
PhpMixed::String(shortcut.clone()),
),
code: 0,
})
.into());
}
}
}
self.options
.insert(option.get_name().to_string(), Rc::clone(&option));
if let Some(shortcut) = option.get_shortcut() {
for shortcut in shirabe_php_shim::explode("|", shortcut) {
self.shortcuts
.insert(shortcut, option.get_name().to_string());
}
}
if option.is_negatable() {
let negated_name = format!("no-{}", option.get_name());
if self.options.contains_key(&negated_name) {
return Err(LogicException(shirabe_php_shim::LogicException {
message: format!(
"An option named \"{}\" already exists.",
PhpMixed::String(negated_name.clone()),
),
code: 0,
})
.into());
}
self.negations
.insert(negated_name, option.get_name().to_string());
}
Ok(())
}
/// Returns an InputOption by name.
pub fn get_option(&self, name: &str) -> anyhow::Result<Rc<InputOption>> {
if !self.has_option(name) {
return Err(
InvalidArgumentException(shirabe_php_shim::InvalidArgumentException {
message: format!(
"The \"--{}\" option does not exist.",
PhpMixed::String(name.to_string()),
),
code: 0,
})
.into(),
);
}
Ok(Rc::clone(&self.options[name]))
}
/// Returns true if an InputOption object exists by name.
///
/// This method can't be used to check if the user included the option when
/// executing the command (use getOption() instead).
pub fn has_option(&self, name: &str) -> bool {
self.options.contains_key(name)
}
/// Gets the array of InputOption objects.
pub fn get_options(&self) -> &IndexMap<String, Rc<InputOption>> {
&self.options
}
/// Returns true if an InputOption object exists by shortcut.
pub fn has_shortcut(&self, name: &str) -> bool {
self.shortcuts.contains_key(name)
}
/// Returns true if an InputOption object exists by negated name.
pub fn has_negation(&self, name: &str) -> bool {
self.negations.contains_key(name)
}
/// Gets an InputOption by shortcut.
pub fn get_option_for_shortcut(&self, shortcut: &str) -> anyhow::Result<Rc<InputOption>> {
self.get_option(&self.shortcut_to_name(shortcut)?)
}
pub fn get_option_defaults(&self) -> IndexMap<String, PhpMixed> {
let mut values = IndexMap::new();
for option in self.options.values() {
values.insert(option.get_name().to_string(), option.get_default().clone());
}
values
}
/// Returns the InputOption name given a shortcut.
pub fn shortcut_to_name(&self, shortcut: &str) -> anyhow::Result<String> {
match self.shortcuts.get(shortcut) {
None => Err(
InvalidArgumentException(shirabe_php_shim::InvalidArgumentException {
message: format!(
"The \"-{}\" option does not exist.",
PhpMixed::String(shortcut.to_string()),
),
code: 0,
})
.into(),
),
Some(name) => Ok(name.clone()),
}
}
/// Returns the InputOption name given a negation.
pub fn negation_to_name(&self, negation: &str) -> anyhow::Result<String> {
match self.negations.get(negation) {
None => Err(
InvalidArgumentException(shirabe_php_shim::InvalidArgumentException {
message: format!(
"The \"--{}\" option does not exist.",
PhpMixed::String(negation.to_string()),
),
code: 0,
})
.into(),
),
Some(name) => Ok(name.clone()),
}
}
/// Gets the synopsis.
pub fn get_synopsis(&self, short: bool) -> String {
let mut elements: Vec<String> = vec![];
if short && !self.get_options().is_empty() {
elements.push("[options]".to_string());
} else if !short {
for option in self.get_options().values() {
let mut value = String::new();
if option.accept_value() {
value = format!(
" {}{}{}",
PhpMixed::String(if option.is_value_optional() {
"[".to_string()
} else {
String::new()
}),
PhpMixed::String(shirabe_php_shim::strtoupper(option.get_name())),
PhpMixed::String(if option.is_value_optional() {
"]".to_string()
} else {
String::new()
}),
);
}
let shortcut = match option.get_shortcut() {
Some(shortcut) => {
format!("-{}|", PhpMixed::String(shortcut.to_string()))
}
None => String::new(),
};
let negation = if option.is_negatable() {
format!("|--no-{}", PhpMixed::String(option.get_name().to_string()),)
} else {
String::new()
};
elements.push(format!(
"[{}--{}{}{}]",
PhpMixed::String(shortcut),
PhpMixed::String(option.get_name().to_string()),
PhpMixed::String(value),
PhpMixed::String(negation),
));
}
}
if !elements.is_empty() && !self.get_arguments().is_empty() {
elements.push("[--]".to_string());
}
let mut tail = String::new();
for argument in self.get_arguments().values() {
let mut element = format!("<{}>", argument.get_name());
if argument.is_array() {
element.push_str("...");
}
if !argument.is_required() {
element = format!("[{}", element);
tail.push(']');
}
elements.push(element);
}
format!("{}{}", shirabe_php_shim::implode(" ", &elements), tail)
}
}
|