Symfony console commands usually work with predefined arguments and options. In most cases, this structured input is exactly what we want. However, there are situations where we may need access to the raw command-line input exactly as it was typed by the user. This tutorial explains how to get raw input in console command in Symfony 8 application.
Symfony provides the getRawTokens method, which allows accessing the raw command-line input exactly as it was entered. By default, getRawTokens includes the original command name as the first element. If we pass the true to the method, the command name is excluded and only the user-provided arguments and options are returned.
src/Command/TestCommand.php
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
protected function configure(): void
{
$this->ignoreValidationErrors();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
// Array([0] => app:test [1] => Hello world [2] => test [3] => -t10 [4] => --bar=foo)
print_r($input->getRawTokens());
// Array([0] => Hello world [1] => test [2] => -t10 [3] => --bar=foo)
print_r($input->getRawTokens(true));
return self::SUCCESS;
}
}
The command for testing:
php bin/console app:test "Hello world" test -t10 --bar=foo
The getRawTokens method is especially handy when we want to handle parsing on our own or forward the full input to another command without needing to define arguments and options in advance. This is useful for wrapper commands around system tools.
src/Command/HostnameCommand.php
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
#[AsCommand(name: 'app:hostname')]
class HostnameCommand extends Command
{
protected function configure(): void
{
$this->ignoreValidationErrors();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$process = new Process(['hostname', ...$input->getRawTokens(true)]);
$process->run();
$output->write(
$process->isSuccessful() ? $process->getOutput() : $process->getErrorOutput()
);
return $process->getExitCode();
}
}
Leave a Comment
Cancel reply