Symfony控制台"问"不接受空值

时间:2016-01-18 03:34:08

标签: php symfony symfony-console

我正在使用symfony控制台包,我在执行命令时要求输入一个值,也就是在public function execute(...)中。

当试图向用户询问某些内容时,我认为如果您没有制作自己的自定义样式,则有两种不同的方式。 a)使用问题助手,b)使用预定义的样式,特此SymfonyStyle
我开始使用运行简单SymfonyStyle的{​​{1}},如果我没有给它一个值,它会一直给我错误。如果我使用帮助器,直接创建问题,那么它将允许我给它一个空值。

以下是一些例子:

ask("question here")

查看# SomeCommand.php namespace What\A\Command; use Symfony\Component\Console\Question\Question; use Symfony\Component\Console\Style\SymfonyStyle; // ... public function execute(InputInterface $input, OutputInterface $output) { // ... // With the helper, which allows empty answer $helper = $this->getHelper('question'); $q = new Question('Question here'); dump($helper->ask($input, $output, $q)); // Output: // Question here // null // With SymfonyStyle which DOES NOT allow empty answer $io = new SymfonyStyle($input, $output); dump($io->ask("Question here")); // Output: // Question here: // [ERROR] A value is required. } 的文件,看起来根本没有与验证有太大不同,正如课程所说,它只是造型。 那么我遗漏的是这两者之间的区别吗?是否有可能让SymfonyStyle完全接受空答案?

3 个答案:

答案 0 :(得分:0)

这是我在这种情况下使用的: (这是$this->io= new SymfonyStyle($input, $output))类的摘录。

在我的用例中,占位符将在用户输入中非常不可能。

public function askAllowEmpty($question, $default)
    {
        $placeholder = \uniqid("placeholder");
        $field = $this->io->ask($question, $default, function($string) use ($placeholder) {
               return (null == $string)? $placeholder : $string;
        });
        return str_replace($placeholder, null, $field);
    }

答案 1 :(得分:0)

我的解决方案:

$question = new Question(
    "Please insert a value",
    false
);

$userInput = $io->askQuestion($question);


$finalValue = $userInput ? $userInput : null;

当用户未插入任何内容时,需要使用最后一行$finalValue作为null(而不是false)。

答案 2 :(得分:0)

实际上,这很简单,只要您了解问题可以得到错误的答案,而不能得到无效的答案。使用SymfonyStyle,可以在一行中完成此操作:

$answer = $this->io->ask("Ask a question?", false) ?: null);

当然,这是假设您不需要错误的答复。