Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/Command/AskForInputCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

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\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

#[AsCommand('app:ask-for-input', 'An example command asking for user input.')]
final class AskForInputCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$helper = $this->getHelper('question');

$question = new ConfirmationQuestion('continue?', false);
if (!$helper->ask($input, $output, $question)) {
$output->writeln('bye');

return Command::FAILURE;
}

$question = new Question('input');
$answer = $helper->ask($input, $output, $question);

$output->writeln("user input: '$answer'");

return Command::SUCCESS;
}
}
32 changes: 31 additions & 1 deletion tests/Functional/ConsoleCest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

namespace App\Tests\Functional;

use App\Command\AskForInputCommand;
use App\Command\ExampleCommand;
use App\Tests\Support\FunctionalTester;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\MissingInputException;

final class ConsoleCest
{
public function runSymfonyConsoleCommand(FunctionalTester $I)
public function runSymfonyConsoleCommand(FunctionalTester $I): void
{
// Call Symfony console without option
$output = $I->runSymfonyConsoleCommand(ExampleCommand::getDefaultName());
Expand All @@ -29,4 +32,31 @@ public function runSymfonyConsoleCommand(FunctionalTester $I)
);
$I->assertStringContainsString('Bye world!', $output);
}

public function runSymfonyConsoleCommandInput(FunctionalTester $I): void
{
// Confirmation question not confirmed
$output = $I->runSymfonyConsoleCommand(
AskForInputCommand::getDefaultName(),
consoleInputs: ['n'],
expectedExitCode: Command::FAILURE,
);
$I->assertStringContainsString('bye', $output);

// Exception on missing input
$I->expectThrowable(
MissingInputException::class,
fn () => $I->runSymfonyConsoleCommand(
AskForInputCommand::getDefaultName(),
consoleInputs: ['y'],
),
);

// Multiple inputs
$output = $I->runSymfonyConsoleCommand(
AskForInputCommand::getDefaultName(),
consoleInputs: ['y', 'foobar'],
);
$I->assertStringContainsString("user input: 'foobar'", $output);
}
}