Command example

class SymfonyStyleTest extends TestCase
{
    protected Command $command;
    protected CommandTester $tester;
    private string|false $colSize;

    protected function setUp(): void
    {
        $this->colSize = getenv('COLUMNS');
        putenv('COLUMNS=121');
        $this->command = new Command('sfstyle');
        $this->tester = new CommandTester($this->command);
    }

    protected function tearDown(): void
    {
        putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
    }

    /** * @dataProvider inputCommandToOutputFilesProvider */
    


    /** * @testWith [true] * [false] */
    public function testSetCatchErrors(bool $catchExceptions)
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions($catchExceptions);
        $application->add((new Command('boom'))->setCode(fn () => throw new \Error('This is an error.')));

        putenv('COLUMNS=120');
        $tester = new ApplicationTester($application);

        try {
            $tester->run(['command' => 'boom']);
            $this->fail('The exception is not catched.');
        } catch (\Throwable $e) {
            $this->assertInstanceOf(\Error::class$e);
            $this->assertSame('This is an error.', $e->getMessage());
        }

        


        $this->assertNull($h);
    }

    public function testConsoleEvent()
    {
        $dispatcher = new EventDispatcher();
        $listener = new DebugHandlersListener(null);
        $app = $this->createMock(Application::class);
        $app->expects($this->once())->method('getHelperSet')->willReturn(new HelperSet());
        $command = new Command(__FUNCTION__);
        $command->setApplication($app);
        $event = new ConsoleEvent($commandnew ArgvInput()new ConsoleOutput());

        $dispatcher->addSubscriber($listener);

        $xListeners = [
            KernelEvents::REQUEST => [[$listener, 'configure']],
            ConsoleEvents::COMMAND => [[$listener, 'configure']],
        ];
        $this->assertSame($xListeners$dispatcher->getListeners());

        
protected static string $fixturesPath;

    public static function setUpBeforeClass(): void
    {
        self::$fixturesPath = __DIR__.'/../Fixtures/';
        require_once self::$fixturesPath.'/TestCommand.php';
    }

    public function testConstructor()
    {
        $command = new Command('foo:bar');
        $this->assertEquals('foo:bar', $command->getName(), '__construct() takes the command name as its first argument');
    }

    public function testCommandNameCannotBeEmpty()
    {
        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name.');
        (new Application())->add(new Command());
    }

    public function testSetApplication()
    {
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Tester\CommandTester;

class CommandTesterTest extends TestCase
{
    protected Command $command;
    protected CommandTester $tester;

    protected function setUp(): void
    {
        $this->command = new Command('foo');
        $this->command->addArgument('command');
        $this->command->addArgument('foo');
        $this->command->setCode(function D$input$output) { $output->writeln('foo')});

        $this->tester = new CommandTester($this->command);
        $this->tester->execute(['foo' => 'bar']['interactive' => false, 'decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]);
    }

    public function testExecute()
    {
        $this->assertFalse($this->tester->getInput()->isInteractive(), '->execute() takes an interactive option');
        
use Symfony\Component\Console\Descriptor\ApplicationDescription;

final class ApplicationDescriptionTest extends TestCase
{
    /** * @dataProvider getNamespacesProvider */
    public function testGetNamespaces(array $expected, array $names)
    {
        $application = new TestApplication();
        foreach ($names as $name) {
            $application->add(new Command($name));
        }

        $this->assertSame($expectedarray_keys((new ApplicationDescription($application))->getNamespaces()));
    }

    public static function getNamespacesProvider()
    {
        return [
            [['_global']['foobar']],
            [['a', 'b']['b:foo', 'a:foo', 'b:bar']],
            [['_global', 22, 33, 'b', 'z']['z:foo', '1', '33:foo', 'b:foo', '22:foo:bar']],
        ];

        $error = new \TypeError('An error occurred');

        $logger = $this->createMock(LoggerInterface::class);
        $logger
            ->expects($this->once())
            ->method('critical')
            ->with('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => 'test:run --foo=baz buzz', 'message' => 'An error occurred'])
        ;

        $listener = new ErrorListener($logger);
        $listener->onConsoleError(new ConsoleErrorEvent(new ArgvInput(['console.php', 'test:run', '--foo=baz', 'buzz'])$this->createMock(OutputInterface::class)$errornew Command('test:run')));
    }

    public function testOnConsoleErrorWithNoCommandAndNoInputString()
    {
        $error = new \RuntimeException('An error occurred');

        $logger = $this->createMock(LoggerInterface::class);
        $logger
            ->expects($this->once())
            ->method('critical')
            ->with('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => 'An error occurred'])
        ;
$kernel = $this->getKernel([$bundle]);

        $application = new Application($kernel);
        $application->all();

        // Calling twice: registration should only be done once.         $application->all();
    }

    public function testBundleSingleCommandIsRetrievable()
    {
        $command = new Command('example');

        $bundle = $this->createBundleMock([$command]);

        $kernel = $this->getKernel([$bundle]);

        $application = new Application($kernel);

        $this->assertSame($command$application->get('example'));
    }

    public function testBundleCommandCanBeFound()
    {
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\DependencyInjection\ServiceLocator;

class ContainerCommandLoaderTest extends TestCase
{
    public function testHas()
    {
        $loader = new ContainerCommandLoader(new ServiceLocator([
            'foo-service' => fn () => new Command('foo'),
            'bar-service' => fn () => new Command('bar'),
        ])['foo' => 'foo-service', 'bar' => 'bar-service']);

        $this->assertTrue($loader->has('foo'));
        $this->assertTrue($loader->has('bar'));
        $this->assertFalse($loader->has('baz'));
    }

    public function testGet()
    {
        $loader = new ContainerCommandLoader(new ServiceLocator([
            
return parent::getRunner($application);
    }

    protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed
    {
        return match ($type) {
            Request::class => Request::createFromGlobals(),
            InputInterface::class => $this->getInput(),
            OutputInterface::class => $this->output ??= new ConsoleOutput(),
            Application::class => $this->console ??= new Application(),
            Command::class => $this->command ??= new Command(),
            default => parent::getArgument($parameter$type),
        };
    }

    protected static function register(GenericRuntime $runtime): GenericRuntime
    {
        $self = new self($runtime->options + ['runtimes' => []]);
        $self->options['runtimes'] += [
            HttpKernelInterface::class => $self,
            Request::class => $self,
            Response::class => $self,
            
return $this->getName();
        }

        return 'Console Tool';
    }

    /** * Registers a new command. */
    public function register(string $name): Command
    {
        return $this->add(new Command($name));
    }

    /** * Adds an array of command objects. * * If a Command is not enabled it will not be added. * * @param Command[] $commands An array of commands * * @return void */
    


        $dispatcher->addSubscriber($handler);

        $dispatcher->addListener(ConsoleEvents::COMMAND, function D) use ($logger) {
            $logger->info('After command message.');
        });
        $dispatcher->addListener(ConsoleEvents::TERMINATE, function D) use ($logger) {
            $logger->info('After terminate message.');
        });

        $event = new ConsoleCommandEvent(new Command('foo')$this->createMock(InputInterface::class)$output);
        $dispatcher->dispatch($event, ConsoleEvents::COMMAND);
        $this->assertStringContainsString('Before command message.', $out = $output->fetch());
        $this->assertStringContainsString('After command message.', $out);

        $event = new ConsoleTerminateEvent(new Command('foo')$this->createMock(InputInterface::class)$output, 0);
        $dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
        $this->assertStringContainsString('Before terminate message.', $out = $output->fetch());
        $this->assertStringContainsString('After terminate message.', $out);
    }
}
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;
use Symfony\Component\Console\Exception\CommandNotFoundException;

class FactoryCommandLoaderTest extends TestCase
{
    public function testHas()
    {
        $loader = new FactoryCommandLoader([
            'foo' => fn () => new Command('foo'),
            'bar' => fn () => new Command('bar'),
        ]);

        $this->assertTrue($loader->has('foo'));
        $this->assertTrue($loader->has('bar'));
        $this->assertFalse($loader->has('baz'));
    }

    public function testGet()
    {
        $loader = new FactoryCommandLoader([
            


use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

require __DIR__.'/autoload.php';

return function Darray $context) {
    $command = new Command('go');
    $command->setCode(function DInputInterface $input, OutputInterface $output) use ($context) {
        $output->write('OK Application '.$context['SOME_VAR']);
    });

    $app = new Application();
    $app->add($command);
    $app->setDefaultCommand('go', true);

    return $app;
};
return $this->getName();
        }

        return 'Console Tool';
    }

    /** * Registers a new command. */
    public function register(string $name): Command
    {
        return $this->add(new Command($name));
    }

    /** * Adds an array of command objects. * * If a Command is not enabled it will not be added. * * @param Command[] $commands An array of commands * * @return void */
    
Home | Imprint | This part of the site doesn't use cookies.