在自定义Symfony命令调用的帮助下摆脱'命令'参数

时间:2014-03-13 09:26:48

标签: symfony

我试图编写一个带有几个可选选项的控制台命令,但其中一个是必需的。如果没有任何选项有值,我想打印命令的帮助说明。这个工作正常,只有一个例外 - 当我打电话给'帮助'手动命令,一个'命令'参数显示在帮助屏幕上。

<?php
require __DIR__ .'/vendor/autoload.php';

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class TestCommand extends Symfony\Component\Console\Command\Command
{
  public function configure()
  {
    $this->setName('test')
      ->setDescription('A test command.')
      ->setHelp('Help message.')
      ->addOption('one', null, InputOption::VALUE_OPTIONAL, 'Option 1', null)
      ->addOption('two', null, InputOption::VALUE_OPTIONAL, 'Option 2', null);
  }

  public function execute(InputInterface $in, OutputInterface $out)
  {
    $helpCommand = $this->getApplication()->get('help');
    $helpCommand->run(new ArrayInput(['command_name' => $this->getName()]), $out);
    return 0;
  }
}

$app = new Symfony\Component\Console\Application;
$app->add(new TestCommand());
$app->run();

以下是help test的输出:

vagrant@precise64:~/sf2-console-test
$ ./run.php help test
Usage:
 test [--one[="..."]] [--two[="..."]]

Options:
 --one                 Option 1
 --two                 Option 2
...

与仅help的输出相比:

vagrant@precise64:~/sf2-console-test
$ ./run.php test
Usage:
 test [--one[="..."]] [--two[="..."]]

Arguments:
 command               The command to execute

Options:
 --one                 Option 1
 --two                 Option 2
...

有没有办法摆脱&#39;命令&#39;参数

&#39;命令&#39;参数是Applicaiton :: getDefaultInputDefinition的一部分,但是在调用help命令之前我已经尝试了$this->getApplication()->getDefinition()->setArguments([]);,它似乎没有什么区别。

使用symfony / console v2.4.2以及dev-master 563254c进行测试

1 个答案:

答案 0 :(得分:1)

显然这就是你需要做的事情:

$args = $this->getNativeDefinition()->getArguments();
foreach ($args as $key => $arg) {
  if ($key === 'command') unset($args[$key]);
}
$this->getNativeDefinition()->setArguments($args);
$helpCommand = $this->getApplication()->get('help');
$helpCommand->run(new ArrayInput(['command_name' => $this->getName()]), $out);
return 0;

在我的情况下,我可以做以下事情,因为我没有任何论据。

$this->getNativeDefinition()->setArguments([]);