A Command object contains all the information that is necessary to describe and run a console command. Use the {@link CommandConfig} class to configure a command: php $config = CommandConfig::create() ->setDescription('List and manage servers') ->beginSubCommand('add') ->setDescription('Add a new server') ->addArgument('host', InputArgument::REQUIRED) ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, null, 80) ->end() ; $command = new Command($config);
Since: 1.0
Author: Bernhard Schussek (bschussek@gmail.com)
 public function testRenderApplicationJson()
 {
     $args = new Args($this->helpCommand->getArgsFormat());
     $status = $this->handler->handle($args, $this->io, $this->command);
     $this->assertStringStartsWith('{"commands":[{"name":"help",', $this->io->fetchOutput());
     $this->assertSame(0, $status);
 }
Example #2
0
    public function testRenderApplicationXml()
    {
        $args = new Args($this->helpCommand->getArgsFormat());
        $status = $this->handler->handle($args, $this->io, $this->command);
        $expected = <<<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<symfony name="The Application" version="1.2.3">
EOF;
        $this->assertStringStartsWith($expected, $this->io->fetchOutput());
        $this->assertSame(0, $status);
    }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function handle(Args $args, IO $io, Command $command)
 {
     $application = $command->getApplication();
     if ($args->isArgumentSet('command')) {
         $theCommand = $application->getCommand($args->getArgument('command'));
         $usage = new CommandHelp($theCommand);
     } else {
         $usage = new ApplicationHelp($application);
     }
     $usage->render($io);
     return 0;
 }
Example #4
0
 /**
  * Adds a command to the collection.
  *
  * If a command exists with the same name in the collection, that command
  * is overwritten.
  *
  * @param Command $command The command to add.
  *
  * @see merge(), replace()
  */
 public function add(Command $command)
 {
     $name = $command->getName();
     $this->commands[$name] = $command;
     if ($shortName = $command->getShortName()) {
         $this->shortNameIndex[$shortName] = $name;
     }
     foreach ($command->getAliases() as $alias) {
         $this->aliasIndex[$alias] = $name;
     }
     ksort($this->aliasIndex);
 }
    public function testRenderApplicationText()
    {
        $args = new Args($this->helpCommand->getArgsFormat());
        $status = $this->handler->handle($args, $this->io, $this->command);
        $expected = <<<'EOF'
The Application version 1.2.3

USAGE
  console
EOF;
        $this->assertStringStartsWith($expected, $this->io->fetchOutput());
        $this->assertSame(0, $status);
    }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function handle(Args $args, IO $io, Command $command)
 {
     $descriptor = new XmlDescriptor();
     $output = new IOOutput($io);
     $application = $command->getApplication();
     $applicationAdapter = new ApplicationAdapter($application);
     if ($args->isArgumentSet('command')) {
         $theCommand = $application->getCommand($args->getArgument('command'));
         $commandAdapter = new CommandAdapter($theCommand, $applicationAdapter);
         $descriptor->describe($output, $commandAdapter);
     } else {
         $descriptor->describe($output, $applicationAdapter);
     }
     return 0;
 }
Example #7
0
 /**
  * @expectedException \Puli\Manager\Api\Server\NoSuchServerException
  */
 public function testDeleteServerFailsIfNotFound()
 {
     $this->serverManager->expects($this->once())->method('hasServer')->with('localhost')->willReturn(false);
     $this->serverManager->expects($this->never())->method('removeServer');
     $args = self::$deleteCommand->parseArgs(new StringArgs('localhost'));
     $this->handler->handleDelete($args);
 }
Example #8
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage The path "/path1" is not mapped in the package "vendor/root".
  */
 public function testDeleteMappingFailsIfNotFound()
 {
     $args = self::$deleteCommand->parseArgs(new StringArgs('/path1'));
     $this->repoManager->expects($this->once())->method('hasRootPathMapping')->with('/path1')->willReturn(false);
     $this->repoManager->expects($this->never())->method('removeRootPathMapping')->with('/path1');
     $this->assertSame(0, $this->handler->handleDelete($args));
 }
Example #9
0
 /**
  * @expectedException \RuntimeException
  */
 public function testDeletePluginFailsIfNotInstalled()
 {
     $args = self::$deleteCommand->parseArgs(new StringArgs('My\\Plugin\\Class'));
     $this->manager->expects($this->once())->method('hasPluginClass')->with('My\\Plugin\\Class')->willReturn(false);
     $this->manager->expects($this->never())->method('removePluginClass');
     $this->handler->handleDelete($args);
 }
Example #10
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage No search criteria specified
  */
 public function testFailIfNoCriteria()
 {
     $args = self::$findCommand->parseArgs(new StringArgs(''));
     $this->repo->expects($this->never())->method('find');
     $this->discovery->expects($this->never())->method('findByType');
     $this->handler->handle($args, $this->io);
 }
Example #11
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage The type "my/type" does not exist in the package "vendor/root".
  */
 public function testDeleteTypeFailsIfNotFound()
 {
     $args = self::$deleteCommand->parseArgs(new StringArgs('my/type'));
     $this->discoveryManager->expects($this->once())->method('hasRootBindingType')->with('my/type')->willReturn(false);
     $this->discoveryManager->expects($this->never())->method('removeRootBindingType');
     $this->assertSame(0, $this->handler->handleRemove($args));
 }
 /**
  * @expectedException \RuntimeException
  */
 public function testDeleteInstallerFailsIfNotFound()
 {
     $args = self::$deleteCommand->parseArgs(new StringArgs('symlink'));
     $this->installerManager->expects($this->once())->method('hasInstallerDescriptor')->with('symlink')->willReturn(false);
     $this->installerManager->expects($this->never())->method('removeRootInstallerDescriptor');
     $this->handler->handleDelete($args);
 }
Example #13
0
 private function parse()
 {
     try {
         $this->parsedArgs = $this->command->parseArgs($this->rawArgs);
     } catch (CannotParseArgsException $e) {
         $this->parseError = $e;
     }
     $this->parsed = true;
 }
Example #14
0
 public function testResetKey()
 {
     $args = self::$resetCommand->parseArgs(new StringArgs('the-key'));
     $this->manager->expects($this->once())->method('removeConfigKey')->with('the-key');
     $statusCode = $this->handler->handleReset($args);
     $this->assertSame(0, $statusCode);
     $this->assertEmpty($this->io->fetchOutput());
     $this->assertEmpty($this->io->fetchErrors());
 }
 public function testGetDefaultTarget()
 {
     $target = new InstallTarget('local', 'symlink', 'public_html');
     $this->targetManager->expects($this->once())->method('getDefaultTarget')->willReturn($target);
     $args = self::$getDefaultCommand->parseArgs(new StringArgs(''));
     $this->assertSame(0, $this->handler->handleGetDefault($args, $this->io));
     $this->assertSame("local\n", $this->io->fetchOutput());
     $this->assertEmpty($this->io->fetchErrors());
 }
Example #16
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Cannot disable bindings in the package "vendor/root".
  */
 public function testDisableBindingFailsIfRoot()
 {
     $args = self::$disableCommand->parseArgs(new StringArgs('ab12'));
     $descriptor = new BindingDescriptor('/path', 'my/type', array(), 'glob');
     $descriptor->load($this->packages->getRootPackage());
     $this->discoveryManager->expects($this->once())->method('findBindings')->with($this->uuid('ab12'))->willReturn(array($descriptor));
     $this->discoveryManager->expects($this->never())->method('disableBinding');
     $this->handler->handleDisable($args, $this->io);
 }
Example #17
0
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Invalid build target "foobar". Expected one of: "all", "factory", "repository", "discovery"
  */
 public function testBuildFailsIfInvalidTarget()
 {
     $args = self::$buildCommand->parseArgs(new StringArgs('foobar'));
     $this->factoryManager->expects($this->never())->method('autoGenerateFactoryClass');
     $this->repoManager->expects($this->never())->method('clearRepository');
     $this->repoManager->expects($this->never())->method('buildRepository');
     $this->discoveryManager->expects($this->never())->method('clearDiscovery');
     $this->discoveryManager->expects($this->never())->method('buildDiscovery');
     $this->handler->handle($args);
 }
Example #18
0
 /**
  * Returns the inherited arguments format of the command.
  *
  * @return ArgsFormat The inherited format.
  *
  * @see CommandConfig::buildArgsFormat()
  */
 private function getBaseFormat()
 {
     if ($this->parentCommand) {
         return $this->parentCommand->getArgsFormat();
     }
     if ($this->application) {
         return $this->application->getGlobalArgsFormat();
     }
     return null;
 }
Example #19
0
 public function testCreate()
 {
     $config = CommandConfig::create()->setName('command')->addAlias('alias1')->addAlias('alias2')->setDescription('Description of the command')->setHelp('The help for %command.name%')->addArgument('argument')->addOption('option', 'o')->setHelperSet($helperSet = new HelperSet());
     $applicationConfig = new ApplicationConfig();
     $application = new ConsoleApplication($applicationConfig);
     $applicationAdapter = new ApplicationAdapter($application);
     $command = new Command($config, $application);
     $adapter = new CommandAdapter($command, $applicationAdapter);
     $this->assertSame('command', $adapter->getName());
     $this->assertEquals(new ArgsFormatInputDefinition($command->getArgsFormat()), $adapter->getDefinition());
     $this->assertEquals(new ArgsFormatInputDefinition($command->getArgsFormat()), $adapter->getNativeDefinition());
     $this->assertSame($command, $adapter->getAdaptedCommand());
     $this->assertSame(array('alias1', 'alias2'), $adapter->getAliases());
     $this->assertSame($applicationAdapter, $adapter->getApplication());
     $this->assertSame('Description of the command', $adapter->getDescription());
     $this->assertSame('The help for %command.name%', $adapter->getHelp());
     $this->assertSame('The help for command', $adapter->getProcessedHelp());
     $this->assertSame($helperSet, $adapter->getHelperSet());
     $this->assertSame('command [-o|--option] [--] <cmd1> [<argument>]', $adapter->getSynopsis());
     $this->assertTrue($adapter->isEnabled());
 }
Example #20
0
    public function testCleanPackages()
    {
        $args = self::$cleanCommand->parseArgs(new StringArgs(''));
        // The not-found package
        $this->packageManager->expects($this->once())->method('removePackage')->with('vendor/package3');
        $expected = <<<EOF
Removing vendor/package3

EOF;
        $this->assertSame(0, $this->handler->handleClean($args, $this->io));
        $this->assertSame($expected, $this->io->fetchOutput());
        $this->assertEmpty($this->io->fetchErrors());
    }
Example #21
0
    public function testInstallNothing()
    {
        $this->assetManager->expects($this->once())->method('getAssetMappings')->willReturn(array());
        $this->installationManager->expects($this->never())->method('prepareInstallation');
        $this->installationManager->expects($this->never())->method('installResource');
        $args = self::$installCommand->parseArgs(new StringArgs(''));
        $expected = <<<EOF
Nothing to install.

EOF;
        $this->assertSame(0, $this->handler->handleInstall($args, $this->io));
        $this->assertSame($expected, $this->io->fetchOutput());
        $this->assertEmpty($this->io->fetchErrors());
    }
Example #22
0
    /**
     * @dataProvider getYears
     */
    public function testListLongFormatsYearDependingOnCurrentYear(DateTime $timestamp, $formattedYear)
    {
        $args = self::$lsCommand->parseArgs(new StringArgs('-l /app'));
        $this->repo->add('/app', new TestDirectory('/app', array($dir1 = new TestDirectory('/app/dir1'))));
        $dir1->getMetadata()->setModificationTime((int) $timestamp->format('U'));
        $dir1->getMetadata()->setSize(12);
        $statusCode = $this->handler->handle($args, $this->io);
        $expected = <<<EOF
TestDirectory 12 Feb 3 {$formattedYear} dir1

EOF;
        $this->assertSame(0, $statusCode);
        $this->assertSame($expected, $this->io->fetchOutput());
        $this->assertEmpty($this->io->fetchErrors());
    }
Example #23
0
    public function testHelpPrintsTextIfAsciiDocNotFound()
    {
        $args = $this->helpCommand->parseArgs(new StringArgs('--help'));
        $this->processLauncher->expects($this->any())->method('isSupported')->will($this->returnValue(true));
        $this->executableFinder->expects($this->never())->method('find');
        $this->processLauncher->expects($this->never())->method('launchProcess');
        $this->handler->setApplicationPage('foobar');
        $status = $this->handler->handle($args, $this->io, $this->command);
        $expected = <<<'EOF'
The Application version 1.2.3

USAGE
  the-app
EOF;
        $this->assertStringStartsWith($expected, $this->io->fetchOutput());
        $this->assertSame(0, $status);
    }
Example #24
0
    public function testPrintTreeWithAbsolutePath()
    {
        $args = self::$treeCommand->parseArgs(new StringArgs('/app'));
        $this->repo->add('/app', new TestDirectory('/app', array(new TestDirectory('/app/dir1', array(new TestFile('/app/dir1/file1'))), new TestDirectory('/app/dir2', array(new TestFile('/app/dir2/file1'), new TestFile('/app/dir2/file2'))), new TestFile('/app/file'), new TestFile('/app/resource1'), new TestFile('/app/resource2'))));
        $expected = <<<EOF
/app
├── dir1
│   └── file1
├── dir2
│   ├── file1
│   └── file2
├── file
├── resource1
└── resource2

8 resources

EOF;
        $this->assertSame(0, $this->handler->handle($args, $this->io));
        $this->assertSame($expected, $this->io->fetchOutput());
        $this->assertEmpty($this->io->fetchErrors());
    }
Example #25
0
 /**
  * @param RawArgs $args
  * @param Command $currentCommand
  *
  * @return ResolveResult
  */
 private function processDefaultSubCommands(RawArgs $args, Command $currentCommand)
 {
     if ($result = $this->processDefaultCommands($args, $currentCommand->getDefaultSubCommands())) {
         return $result;
     }
     // No default commands, return the current command
     return new ResolveResult($currentCommand, $args);
 }
Example #26
0
 /**
  * Callback for selecting the handler that should be run.
  *
  * @param Args    $args    The console arguments.
  * @param IO      $io      The I/O.
  * @param Command $command The handled command.
  *
  * @return string The name of the handler to run.
  */
 public function getHandlerToRun(Args $args, IO $io, Command $command)
 {
     $rawArgs = $args->getRawArgs();
     // The raw arguments should always be available, but check anyway
     if (!$rawArgs) {
         return 'text';
     }
     // If "-h" is given, always print the short text usage
     if ($rawArgs->hasToken('-h')) {
         return 'text';
     }
     // Check if any of the options is set
     foreach ($this->getRegisteredNames() as $handlerName) {
         if ($rawArgs->hasToken('--' . $handlerName)) {
             return $handlerName;
         }
     }
     // No format option is set, "-h" is not set
     // If a command is given or if "--help" is set, display the manual
     if ($rawArgs->hasToken('--help')) {
         // Return "man" if the binary is available and the man page exists
         // The process launcher must be supported on the system
         $manPage = $this->getManPage($command->getApplication(), $args);
         if (file_exists($manPage) && $this->processLauncher->isSupported()) {
             if (!$this->manBinary) {
                 $this->manBinary = $this->executableFinder->find('man');
             }
             if ($this->manBinary) {
                 return 'man';
             }
         }
         // Return "ascii-doc" if the AsciiDoc page exists
         $asciiDocPage = $this->getAsciiDocPage($command->getApplication(), $args);
         if (file_exists($asciiDocPage)) {
             return 'ascii-doc';
         }
     }
     // No command, no option -> display command list as text
     return 'text';
 }
Example #27
0
 /**
  * Renders a command in the "Commands" section.
  *
  * @param BlockLayout $layout  The layout.
  * @param Command     $command The command to describe.
  */
 protected function renderCommand(BlockLayout $layout, Command $command)
 {
     $description = $command->getConfig()->getDescription();
     $name = '<c1>' . $command->getName() . '</c1>';
     $layout->add(new LabeledParagraph($name, $description));
 }
Example #28
0
 /**
  * Renders a sub-command in the "Commands" section.
  *
  * @param BlockLayout $layout  The layout.
  * @param Command     $command The command to render.
  */
 protected function renderSubCommand(BlockLayout $layout, Command $command)
 {
     $config = $command->getConfig();
     $description = $config->getDescription();
     $help = $config->getHelp();
     $arguments = $command->getArgsFormat()->getArguments(false);
     $options = $command->getArgsFormat()->getOptions(false);
     if ($config instanceof OptionCommandConfig) {
         if ($config->isLongNamePreferred()) {
             $preferredName = '--<u>' . $config->getLongName() . '</u>';
             $alternativeName = $config->getShortName() ? '-<u>' . $config->getShortName() . '</u>' : null;
         } else {
             $preferredName = '-<u>' . $config->getShortName() . '</u>';
             $alternativeName = '--<u>' . $config->getLongName() . '</u>';
         }
         $name = $preferredName;
         if ($alternativeName) {
             $name .= ' (' . $alternativeName . ')';
         }
     } else {
         $name = '<u>' . $command->getName() . '</u>';
     }
     $layout->add(new Paragraph($name));
     $layout->beginBlock();
     if ($description) {
         $this->renderSubCommandDescription($layout, $description);
     }
     if ($help) {
         $this->renderSubCommandHelp($layout, $help);
     }
     if ($arguments) {
         $this->renderSubCommandArguments($layout, $arguments);
     }
     if ($options) {
         $this->renderSubCommandOptions($layout, $options);
     }
     if (!$description && !$help && !$arguments && !$options) {
         $layout->add(new EmptyLine());
     }
     $layout->endBlock();
 }
Example #29
0
 public function testRunWithLenientArgsParsing()
 {
     $rawArgs = $this->getMock('Webmozart\\Console\\Api\\Args\\RawArgs');
     $parsedArgs = new Args(new ArgsFormat());
     $io = $this->getMockBuilder('Webmozart\\Console\\Api\\IO\\IO')->disableOriginalConstructor()->getMock();
     $parser = $this->getMock('Webmozart\\Console\\Api\\Args\\ArgsParser');
     $handler = $this->getMock('stdClass', array('handle'));
     $config = new CommandConfig('command');
     $config->setArgsParser($parser);
     $config->setHandler($handler);
     $config->enableLenientArgsParsing();
     $command = new Command($config);
     $format = $command->getArgsFormat();
     $parser->expects($this->once())->method('parseArgs')->with($this->identicalTo($rawArgs), $this->identicalTo($format), true)->willReturn($parsedArgs);
     $handler->expects($this->once())->method('handle')->with($parsedArgs, $io, $command)->willReturn(123);
     $this->assertSame(123, $command->run($rawArgs, $io));
 }