From 6051927c8fa32cfffa102d2a170c5a6cf747a1b9 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sun, 9 Aug 2026 11:19:03 +0900 Subject: refactor(symfony-console): extract symfony/console into the shirabe-symfony-console crate Move `Symfony\Component\Console` out of shirabe-external-packages and into its own crate, so the path is `shirabe_symfony_console::application::Application` instead of `shirabe_external_packages::symfony::console::application::Application`. The `delegate_to_inner!` and `delegate_command_trait_impls_to_inner!` macros move with it. Co-Authored-By: Claude Opus 5 (1M context) --- .../symfony/console/question/choice_question.rs | 286 ---------------- .../console/question/confirmation_question.rs | 113 ------- .../src/symfony/console/question/question.rs | 371 --------------------- 3 files changed, 770 deletions(-) delete mode 100644 crates/shirabe-external-packages/src/symfony/console/question/choice_question.rs delete mode 100644 crates/shirabe-external-packages/src/symfony/console/question/confirmation_question.rs delete mode 100644 crates/shirabe-external-packages/src/symfony/console/question/question.rs (limited to 'crates/shirabe-external-packages/src/symfony/console/question') diff --git a/crates/shirabe-external-packages/src/symfony/console/question/choice_question.rs b/crates/shirabe-external-packages/src/symfony/console/question/choice_question.rs deleted file mode 100644 index 52316cf4..00000000 --- a/crates/shirabe-external-packages/src/symfony/console/question/choice_question.rs +++ /dev/null @@ -1,286 +0,0 @@ -//! ref: composer/vendor/symfony/console/Question/ChoiceQuestion.php - -use crate::symfony::console::exception::invalid_argument_exception::InvalidArgumentException; -use crate::symfony::console::exception::logic_exception::LogicException; -use crate::symfony::console::question::Question; -use crate::symfony::console::question::QuestionInterface; -use indexmap::IndexMap; -use shirabe_php_shim::{PhpMixed, php_regex}; - -/// Represents a choice question. -#[derive(Debug)] -pub struct ChoiceQuestion { - inner: Question, - choices: IndexMap, - multiselect: bool, - prompt: String, - error_message: String, -} - -impl ChoiceQuestion { - /// `$question` The question to ask to the user. - /// `$choices` The list of available choices. - /// `$default` The default answer to return. - pub fn new( - question: String, - choices: IndexMap, - default: Option, - ) -> Result { - if choices.is_empty() { - return Err(LogicException::new( - "Choice question must have at least 1 choice available.".to_string(), - )); - } - - let mut this = Self { - inner: Question::new(question, default), - choices: choices.clone(), - multiselect: false, - prompt: " > ".to_string(), - error_message: "Value \"%s\" is invalid".to_string(), - }; - - let validator = this.get_default_validator(); - this.inner.set_validator(Some(validator)); - // setAutocompleterValues never throws for an array argument. - this.inner - .set_autocompleter_values(Some(PhpMixed::Array(choices))) - .expect("autocompleter cannot be set on a hidden question during construction"); - - Ok(this) - } - - /// Returns available choices. - pub fn get_choices(&self) -> &IndexMap { - &self.choices - } - - /// Sets multiselect option. - /// - /// When multiselect is set to true, multiple choices can be answered. - pub fn set_multiselect(&mut self, multiselect: bool) -> &mut Self { - self.multiselect = multiselect; - let validator = self.get_default_validator(); - self.inner.set_validator(Some(validator)); - - self - } - - /// Returns whether the choices are multiselect. - pub fn is_multiselect(&self) -> bool { - self.multiselect - } - - /// Gets the prompt for choices. - pub fn get_prompt(&self) -> &str { - &self.prompt - } - - /// Sets the prompt for choices. - pub fn set_prompt(&mut self, prompt: String) -> &mut Self { - self.prompt = prompt; - - self - } - - /// Inherited from Question. Sets the maximum number of attempts. - pub fn set_max_attempts( - &mut self, - attempts: Option, - ) -> Result<&mut Self, InvalidArgumentException> { - self.inner.set_max_attempts(attempts)?; - - Ok(self) - } - - /// Sets the error message for invalid values. - /// - /// The error message has a string placeholder (%s) for the invalid value. - pub fn set_error_message(&mut self, error_message: String) -> &mut Self { - self.error_message = error_message; - let validator = self.get_default_validator(); - self.inner.set_validator(Some(validator)); - - self - } - - fn get_default_validator( - &self, - ) -> Box) -> Result> { - let choices = self.choices.clone(); - let error_message = self.error_message.clone(); - let multiselect = self.multiselect; - let is_assoc = Question::is_assoc(&PhpMixed::Array(self.choices.clone())); - // PHP reads `$this->isTrimmable()` live inside the closure. A 'static boxed - // closure cannot borrow `$this`, so the value is snapshotted at validator - // creation time. setValidator is re-run on multiselect/errorMessage changes, - // but a later setTrimmable would not be reflected. See review notes. - let trimmable = self.inner.is_trimmable(); - - Box::new(move |selected: Option| { - let selected = selected.unwrap_or(PhpMixed::Null); - - let selected_choices: Vec = if multiselect { - // Check for a separated comma values - let mut matches: Vec> = Vec::new(); - if !shirabe_php_shim::preg_match( - php_regex!("/^[^,]+(?:,[^,]+)*$/"), - &shirabe_php_shim::strval(&selected), - &mut matches, - ) { - return Err(InvalidArgumentException::new(shirabe_php_shim::sprintf( - &error_message, - std::slice::from_ref(&selected), - ))); - } - - shirabe_php_shim::explode(",", &shirabe_php_shim::strval(&selected)) - .into_iter() - .map(PhpMixed::String) - .collect() - } else { - vec![selected] - }; - - let mut selected_choices = selected_choices; - if trimmable { - for v in selected_choices.iter_mut() { - *v = PhpMixed::String(shirabe_php_shim::trim( - &shirabe_php_shim::strval(v), - None, - )); - } - } - - let mut multiselect_choices: Vec = Vec::new(); - for value in &selected_choices { - let mut results: Vec = Vec::new(); - for (key, choice) in &choices { - if (*choice) == *value { - results.push(key.clone()); - } - } - - if results.len() > 1 { - return Err(InvalidArgumentException::new(format!( - "The provided answer is ambiguous. Value should be one of \"{}\".", - shirabe_php_shim::implode("\" or \"", &results), - ))); - } - - // array_search($value, $choices) - let result_key = shirabe_php_shim::array_search( - &shirabe_php_shim::strval(value), - &choices_as_str(&choices), - ); - - let mut result: PhpMixed; - if !is_assoc { - if let Some(found_key) = &result_key { - // $result = $choices[$result]; - result = choices[found_key].clone(); - } else if let Some(found) = choices.get(&shirabe_php_shim::strval(value)) { - // isset($choices[$value]) - result = found.clone(); - } else { - result = PhpMixed::Bool(false); - } - } else if result_key.is_none() { - if let Some(_found) = choices.get(&shirabe_php_shim::strval(value)) { - // false === $result && isset($choices[$value]) - result = value.clone(); - } else { - result = PhpMixed::Bool(false); - } - } else { - // associative, found: keep the matched key - result = PhpMixed::String(result_key.clone().unwrap()); - } - - // false === $result - if matches!(result, PhpMixed::Bool(false)) { - return Err(InvalidArgumentException::new(shirabe_php_shim::sprintf( - &error_message, - std::slice::from_ref(value), - ))); - } - - // For associative choices, consistently return the key as string: - if is_assoc { - result = PhpMixed::String(shirabe_php_shim::strval(&result)); - } - multiselect_choices.push(result); - } - - if multiselect { - return Ok(PhpMixed::List(multiselect_choices)); - } - - Ok(multiselect_choices - .into_iter() - .next() - .unwrap_or(PhpMixed::Bool(false))) - }) - } -} - -impl QuestionInterface for ChoiceQuestion { - fn get_question(&self) -> &str { - self.inner.get_question() - } - - fn get_default(&self) -> PhpMixed { - self.inner.get_default() - } - - fn is_multiline(&self) -> bool { - self.inner.is_multiline() - } - - fn is_hidden(&self) -> bool { - self.inner.is_hidden() - } - - fn is_hidden_fallback(&self) -> bool { - self.inner.is_hidden_fallback() - } - - fn get_autocompleter_values(&self) -> Option> { - self.inner.get_autocompleter_values() - } - - fn get_autocompleter_callback(&self) -> Option<&dyn Fn(&str) -> Option>> { - self.inner.get_autocompleter_callback() - } - - fn get_validator( - &self, - ) -> Option<&dyn Fn(Option) -> Result> { - self.inner.get_validator() - } - - fn get_max_attempts(&self) -> Option { - self.inner.get_max_attempts() - } - - fn get_normalizer(&self) -> Option<&dyn Fn(PhpMixed) -> PhpMixed> { - self.inner.get_normalizer() - } - - fn is_trimmable(&self) -> bool { - self.inner.is_trimmable() - } - - fn as_choice(&self) -> Option<&ChoiceQuestion> { - Some(self) - } -} - -/// array_search operates over the choice values as strings; this projects the -/// choices map's values into the string-keyed form the shim expects. -fn choices_as_str(choices: &IndexMap) -> IndexMap { - choices - .iter() - .map(|(k, v)| (k.clone(), shirabe_php_shim::strval(v))) - .collect() -} diff --git a/crates/shirabe-external-packages/src/symfony/console/question/confirmation_question.rs b/crates/shirabe-external-packages/src/symfony/console/question/confirmation_question.rs deleted file mode 100644 index 4a050461..00000000 --- a/crates/shirabe-external-packages/src/symfony/console/question/confirmation_question.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! ref: composer/vendor/symfony/console/Question/ConfirmationQuestion.php - -use crate::symfony::console::exception::invalid_argument_exception::InvalidArgumentException; -use crate::symfony::console::question::Question; -use crate::symfony::console::question::QuestionInterface; -use shirabe_php_shim::PhpMixed; - -/// Represents a yes/no question. -#[derive(Debug)] -pub struct ConfirmationQuestion { - inner: Question, - true_answer_regex: String, -} - -impl ConfirmationQuestion { - /// `$question` The question to ask to the user. - /// `$default` The default answer to return, true or false. - /// `$trueAnswerRegex` A regex to match the "yes" answer. - pub fn new(question: String, default: bool, true_answer_regex: String) -> Self { - let mut this = Self { - inner: Question::new(question, Some(PhpMixed::Bool(default))), - true_answer_regex, - }; - - let normalizer = this.get_default_normalizer(); - this.inner.set_normalizer(normalizer); - - this - } - - /// Returns the default answer normalizer. - fn get_default_normalizer(&self) -> Box PhpMixed> { - let default = self.inner.get_default(); - let regex = self.true_answer_regex.clone(); - - Box::new(move |answer: PhpMixed| { - if let PhpMixed::Bool(_) = answer { - return answer; - } - - let answer_is_true = { - let mut matches: Vec> = Vec::new(); - shirabe_php_shim::preg_match( - ®ex, - &shirabe_php_shim::strval(&answer), - &mut matches, - ) - }; - - // false === $default - if matches!(default, PhpMixed::Bool(false)) { - // $answer && $answerIsTrue - return PhpMixed::Bool(!shirabe_php_shim::empty(&answer) && answer_is_true); - } - - // '' === $answer || $answerIsTrue - let answer_is_empty_string = matches!(&answer, PhpMixed::String(s) if s.is_empty()); - PhpMixed::Bool(answer_is_empty_string || answer_is_true) - }) - } -} - -impl QuestionInterface for ConfirmationQuestion { - fn get_question(&self) -> &str { - self.inner.get_question() - } - - fn get_default(&self) -> PhpMixed { - self.inner.get_default() - } - - fn is_multiline(&self) -> bool { - self.inner.is_multiline() - } - - fn is_hidden(&self) -> bool { - self.inner.is_hidden() - } - - fn is_hidden_fallback(&self) -> bool { - self.inner.is_hidden_fallback() - } - - fn get_autocompleter_values(&self) -> Option> { - self.inner.get_autocompleter_values() - } - - fn get_autocompleter_callback(&self) -> Option<&dyn Fn(&str) -> Option>> { - self.inner.get_autocompleter_callback() - } - - fn get_validator( - &self, - ) -> Option<&dyn Fn(Option) -> Result> { - self.inner.get_validator() - } - - fn get_max_attempts(&self) -> Option { - self.inner.get_max_attempts() - } - - fn get_normalizer(&self) -> Option<&dyn Fn(PhpMixed) -> PhpMixed> { - self.inner.get_normalizer() - } - - fn is_trimmable(&self) -> bool { - self.inner.is_trimmable() - } - - fn as_confirmation(&self) -> Option<&ConfirmationQuestion> { - Some(self) - } -} diff --git a/crates/shirabe-external-packages/src/symfony/console/question/question.rs b/crates/shirabe-external-packages/src/symfony/console/question/question.rs deleted file mode 100644 index 165f287e..00000000 --- a/crates/shirabe-external-packages/src/symfony/console/question/question.rs +++ /dev/null @@ -1,371 +0,0 @@ -//! ref: composer/vendor/symfony/console/Question/Question.php - -use crate::symfony::console::exception::invalid_argument_exception::InvalidArgumentException; -use crate::symfony::console::exception::logic_exception::LogicException; -use crate::symfony::console::question::choice_question::ChoiceQuestion; -use crate::symfony::console::question::confirmation_question::ConfirmationQuestion; -use shirabe_php_shim::PhpMixed; - -/// Polymorphic boundary for the Symfony Console Question hierarchy. -/// -/// PHP has no `QuestionInterface`; `Question` is a concrete class extended by -/// `ChoiceQuestion`/`ConfirmationQuestion`. Modelling those subclasses as -/// `inner: Question` composition loses subtype identity, so consumers that take -/// a `Question` and run `instanceof` checks are expressed here as a trait whose -/// `as_choice`/`as_confirmation` downcasts stand in for `instanceof`. -pub trait QuestionInterface: std::fmt::Debug { - fn get_question(&self) -> &str; - - fn get_default(&self) -> PhpMixed; - - fn is_multiline(&self) -> bool; - - fn is_hidden(&self) -> bool; - - fn is_hidden_fallback(&self) -> bool; - - fn get_autocompleter_values(&self) -> Option>; - - fn get_autocompleter_callback(&self) -> Option<&dyn Fn(&str) -> Option>>; - - fn get_validator( - &self, - ) -> Option<&dyn Fn(Option) -> Result>; - - fn get_max_attempts(&self) -> Option; - - fn get_normalizer(&self) -> Option<&dyn Fn(PhpMixed) -> PhpMixed>; - - fn is_trimmable(&self) -> bool; - - /// Models `$question instanceof ChoiceQuestion`. - fn as_choice(&self) -> Option<&ChoiceQuestion> { - None - } - - /// Models `$question instanceof ConfirmationQuestion`. - fn as_confirmation(&self) -> Option<&ConfirmationQuestion> { - None - } -} - -/// Represents a Question. -pub struct Question { - question: String, - attempts: Option, - hidden: bool, - hidden_fallback: bool, - autocompleter_callback: Option Option>>>, - validator: Option) -> Result>>, - default: Option, - normalizer: Option PhpMixed>>, - trimmable: bool, - multiline: bool, -} - -impl std::fmt::Debug for Question { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Question") - .field("question", &self.question) - .field("attempts", &self.attempts) - .field("hidden", &self.hidden) - .field("hidden_fallback", &self.hidden_fallback) - .field("default", &self.default) - .field("trimmable", &self.trimmable) - .field("multiline", &self.multiline) - .finish_non_exhaustive() - } -} - -impl Question { - /// `$question` The question to ask to the user. - /// `$default` The default answer to return if the user enters nothing. - pub fn new(question: String, default: Option) -> Self { - Self { - question, - attempts: None, - hidden: false, - hidden_fallback: true, - autocompleter_callback: None, - validator: None, - default, - normalizer: None, - trimmable: true, - multiline: false, - } - } - - /// Returns the question. - pub fn get_question(&self) -> &str { - &self.question - } - - /// Returns the default answer. - pub fn get_default(&self) -> PhpMixed { - self.default.clone().unwrap_or(PhpMixed::Null) - } - - /// Returns whether the user response accepts newline characters. - pub fn is_multiline(&self) -> bool { - self.multiline - } - - /// Sets whether the user response should accept newline characters. - pub fn set_multiline(&mut self, multiline: bool) -> &mut Self { - self.multiline = multiline; - - self - } - - /// Returns whether the user response must be hidden. - pub fn is_hidden(&self) -> bool { - self.hidden - } - - /// Sets whether the user response must be hidden or not. - /// - /// Throws LogicException in case the autocompleter is also used. - pub fn set_hidden(&mut self, hidden: bool) -> Result<&mut Self, LogicException> { - if self.autocompleter_callback.is_some() { - return Err(LogicException::new( - "A hidden question cannot use the autocompleter.".to_string(), - )); - } - - self.hidden = hidden; - - Ok(self) - } - - /// In case the response cannot be hidden, whether to fallback on non-hidden question or not. - pub fn is_hidden_fallback(&self) -> bool { - self.hidden_fallback - } - - /// Sets whether to fallback on non-hidden question if the response cannot be hidden. - pub fn set_hidden_fallback(&mut self, fallback: bool) -> &mut Self { - self.hidden_fallback = fallback; - - self - } - - /// Gets values for the autocompleter. - pub fn get_autocompleter_values(&self) -> Option> { - let callback = self.get_autocompleter_callback(); - - match callback { - Some(callback) => callback(""), - None => None, - } - } - - /// Sets values for the autocompleter. - /// - /// Throws LogicException. - pub fn set_autocompleter_values( - &mut self, - values: Option, - ) -> Result<&mut Self, LogicException> { - let callback: Option Option>>> = match values { - // PHP: `if (\is_array($values))`. Both PhpMixed::List and ::Array model PHP arrays. - Some(values) if matches!(values, PhpMixed::List(_) | PhpMixed::Array(_)) => { - let values = if Self::is_assoc(&values) { - let array = match &values { - PhpMixed::Array(array) => array, - _ => unreachable!(), - }; - // array_merge(array_keys($values), array_values($values)) - let mut merged: Vec = - array.keys().map(|k| PhpMixed::String(k.clone())).collect(); - merged.extend(array.values().cloned()); - merged - } else { - // array_values($values) - match &values { - PhpMixed::List(list) => list.to_vec(), - PhpMixed::Array(array) => array.values().cloned().collect(), - _ => unreachable!(), - } - }; - - Some(Box::new(move |_input: &str| Some(values.clone()))) - } - // PHP: `elseif ($values instanceof \Traversable)`. In PHP this caches the - // iterator result; here non-array iterables are not modeled, so treat any - // remaining value as the Traversable branch. - Some(values) => { - // PHP: `iterator_to_array($values, false)` caches a Traversable. - // Non-array iterables are not modeled by PhpMixed; extract any - // list/array elements, otherwise treat as an empty iterator. - let cached: Vec = match values { - PhpMixed::List(list) => list.into_iter().collect(), - PhpMixed::Array(array) => array.into_values().collect(), - _ => Vec::new(), - }; - Some(Box::new(move |_input: &str| Some(cached.clone()))) - } - None => None, - }; - - self.set_autocompleter_callback(callback) - } - - /// Gets the callback function used for the autocompleter. - pub fn get_autocompleter_callback(&self) -> Option<&dyn Fn(&str) -> Option>> { - self.autocompleter_callback.as_deref() - } - - /// Sets the callback function used for the autocompleter. - /// - /// The callback is passed the user input as argument and should return an iterable of - /// corresponding suggestions. - pub fn set_autocompleter_callback( - &mut self, - callback: Option Option>>>, - ) -> Result<&mut Self, LogicException> { - if self.hidden && callback.is_some() { - return Err(LogicException::new( - "A hidden question cannot use the autocompleter.".to_string(), - )); - } - - self.autocompleter_callback = callback; - - Ok(self) - } - - /// Sets a validator for the question. - pub fn set_validator( - &mut self, - validator: Option< - Box) -> Result>, - >, - ) -> &mut Self { - self.validator = validator; - - self - } - - /// Gets the validator for the question. - pub fn get_validator( - &self, - ) -> Option<&dyn Fn(Option) -> Result> { - self.validator.as_deref() - } - - /// Sets the maximum number of attempts. - /// - /// Null means an unlimited number of attempts. - /// - /// Throws InvalidArgumentException in case the number of attempts is invalid. - pub fn set_max_attempts( - &mut self, - attempts: Option, - ) -> Result<&mut Self, InvalidArgumentException> { - if let Some(attempts) = attempts - && attempts < 1 - { - return Err(InvalidArgumentException::new( - "Maximum number of attempts must be a positive value.".to_string(), - )); - } - - self.attempts = attempts; - - Ok(self) - } - - /// Gets the maximum number of attempts. - /// - /// Null means an unlimited number of attempts. - pub fn get_max_attempts(&self) -> Option { - self.attempts - } - - /// Sets a normalizer for the response. - /// - /// The normalizer can be a callable (a string), a closure or a class implementing __invoke. - pub fn set_normalizer(&mut self, normalizer: Box PhpMixed>) -> &mut Self { - self.normalizer = Some(normalizer); - - self - } - - /// Gets the normalizer for the response. - /// - /// The normalizer can ba a callable (a string), a closure or a class implementing __invoke. - pub fn get_normalizer(&self) -> Option<&dyn Fn(PhpMixed) -> PhpMixed> { - self.normalizer.as_deref() - } - - // PHP: `(bool) \count(array_filter(array_keys($array), 'is_string'))`. - // A `List` has only sequential int keys, so it is never associative. An `Array` is - // associative only when at least one key is a genuine string key; PHP normalizes - // canonical-integer string keys (e.g. "0", "12") back to int keys, so those do not count. - // The same heuristic (a key is "string" iff it does not parse as an i64) is used by - // ConsoleIO::select when computing `$isAssoc` over the choice map. - pub(crate) fn is_assoc(array: &PhpMixed) -> bool { - match array { - PhpMixed::Array(map) => map.keys().any(|key| key.parse::().is_err()), - _ => false, - } - } - - pub fn is_trimmable(&self) -> bool { - self.trimmable - } - - pub fn set_trimmable(&mut self, trimmable: bool) -> &mut Self { - self.trimmable = trimmable; - - self - } -} - -impl QuestionInterface for Question { - fn get_question(&self) -> &str { - self.get_question() - } - - fn get_default(&self) -> PhpMixed { - self.get_default() - } - - fn is_multiline(&self) -> bool { - self.is_multiline() - } - - fn is_hidden(&self) -> bool { - self.is_hidden() - } - - fn is_hidden_fallback(&self) -> bool { - self.is_hidden_fallback() - } - - fn get_autocompleter_values(&self) -> Option> { - self.get_autocompleter_values() - } - - fn get_autocompleter_callback(&self) -> Option<&dyn Fn(&str) -> Option>> { - self.get_autocompleter_callback() - } - - fn get_validator( - &self, - ) -> Option<&dyn Fn(Option) -> Result> { - self.get_validator() - } - - fn get_max_attempts(&self) -> Option { - self.get_max_attempts() - } - - fn get_normalizer(&self) -> Option<&dyn Fn(PhpMixed) -> PhpMixed> { - self.get_normalizer() - } - - fn is_trimmable(&self) -> bool { - self.is_trimmable() - } -} -- cgit v1.3.1-4-g156e