Ejemplo n.º 1
0
 /**
  * Validates an attempt.
  *
  * @param callable        $interviewer  A callable that will ask for a question and return the result
  * @param OutputInterface $output       An Output instance
  * @param Question        $question     A Question instance
  *
  * @return string   The validated response
  *
  * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  */
 private function validateAttempts($interviewer, OutputInterface $output, Question $question)
 {
     $error = null;
     $attempts = $question->getMaxAttempts();
     while (null === $attempts || $attempts--) {
         if (null !== $error) {
             $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'));
         }
         try {
             return call_user_func($question->getValidator(), $interviewer());
         } catch (\Exception $error) {
         }
     }
     throw $error;
 }
Ejemplo n.º 2
0
 public function testAskAndValidate()
 {
     $dialog = new QuestionHelper();
     $helperSet = new HelperSet(array(new FormatterHelper()));
     $dialog->setHelperSet($helperSet);
     $error = 'This is not a color!';
     $validator = function ($color) use($error) {
         if (!in_array($color, array('white', 'black'))) {
             throw new \InvalidArgumentException($error);
         }
         return $color;
     };
     $question = new Question('What color was the white horse of Henry IV?', 'white');
     $question->setValidator($validator);
     $question->setMaxAttempts(2);
     $dialog->setInputStream($this->getInputStream("\nblack\n"));
     $this->assertEquals('white', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('black', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $dialog->setInputStream($this->getInputStream("green\nyellow\norange\n"));
     try {
         $this->assertEquals('white', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
         $this->fail();
     } catch (\InvalidArgumentException $e) {
         $this->assertEquals($error, $e->getMessage());
     }
 }