diff --git a/console/input.rst b/console/input.rst index ed4e723b953..2326145afce 100644 --- a/console/input.rst +++ b/console/input.rst @@ -825,6 +825,56 @@ command without having to worry about the number of arguments or options:: // ... } +Accessing Raw Arguments and Options +----------------------------------- + +While ``getRawTokens()`` returns the unparsed CLI tokens as strings, sometimes +you need access to the *parsed* arguments and options without default values +merged in. The :class:`Symfony\\Component\\Console\\Input\\RawInputInterface` +provides methods for this: + +* ``getRawArguments()``: returns only arguments explicitly passed by the user + (without default values merged in); +* ``getRawOptions()``: returns only options explicitly passed by the user + (without default values merged in); +* ``unparse()``: converts parsed options back to their CLI string representation + (e.g. ``['--format=json', '--verbose']``). + +You can type-hint ``RawInputInterface`` in invokable commands to access these +methods:: + + // ... + use Symfony\Component\Console\Input\RawInputInterface; + use Symfony\Component\Console\Output\OutputInterface; + use Symfony\Component\Process\Process; + + public function __invoke(RawInputInterface $input, OutputInterface $output): int + { + // returns only arguments explicitly passed (no defaults) + $rawArguments = $input->getRawArguments(); + + // returns only options explicitly passed (no defaults) + $rawOptions = $input->getRawOptions(); + + // converts parsed options back to CLI tokens, useful for forwarding + // to a child process + $process = new Process([ + 'app:child-command', + ...$input->getRawArguments(), + ...$input->unparse(), + ]); + $process->mustRun(); + + // you can also filter specific options to unparse + $unparsed = $input->unparse(['format', 'verbose']); + + // ... + } + +.. versionadded:: 8.1 + + The ``RawInputInterface`` was introduced in Symfony 8.1. + .. _console-input-completion: Adding Argument/Option Value Completion