4 * This file is part of the Behat.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Behat\Context\Cli;
13 use Behat\Behat\Context\Environment\ContextEnvironment;
14 use Behat\Behat\Context\Snippet\Generator\TargetContextIdentifier;
15 use Symfony\Component\Console\Helper\QuestionHelper;
16 use Symfony\Component\Console\Input\InputInterface;
17 use Symfony\Component\Console\Output\OutputInterface;
18 use Symfony\Component\Console\Question\ChoiceQuestion;
19 use Symfony\Component\Translation\TranslatorInterface;
22 * Interactive identifier that asks user for input.
24 * @author Konstantin Kudryashov <ever.zet@gmail.com>
26 final class InteractiveContextIdentifier implements TargetContextIdentifier
29 * @var TranslatorInterface
37 * @var OutputInterface
42 * Initialises identifier.
44 * @param TranslatorInterface $translator
45 * @param InputInterface $input
46 * @param OutputInterface $output
48 public function __construct(TranslatorInterface $translator, InputInterface $input, OutputInterface $output)
50 $this->translator = $translator;
51 $this->input = $input;
52 $this->output = $output;
58 public function guessTargetContextClass(ContextEnvironment $environment)
60 if ($this->interactionIsNotSupported()) {
64 $suiteName = $environment->getSuite()->getName();
65 $contextClasses = $environment->getContextClasses();
67 if (!count($contextClasses)) {
71 $message = $this->translator->trans('snippet_context_choice', array('%1%' => $suiteName), 'output');
72 $choices = array_values(array_merge(array('None'), $contextClasses));
73 $default = current($contextClasses);
75 $answer = $this->askQuestion('>> ' . $message, $choices, $default);
77 return 'None' !== $answer ? $answer : null;
83 * @param string $message
84 * @param string[] $choices
85 * @param string $default
89 private function askQuestion($message, $choices, $default)
91 $this->output->writeln('');
92 $helper = new QuestionHelper();
93 $question = new ChoiceQuestion(' ' . $message . "\n", $choices, $default);
95 return $helper->ask($this->input, $this->output, $question);
99 * Checks if interactive mode is supported.
103 * @deprecated there is a better way to do it - `InputInterface::isInteractive()` method.
104 * Sadly, this doesn't work properly prior Symfony\Console 2.7 and as we need
105 * to support 2.5+ until the next major, we are forced to do a more explicit
106 * check for the CLI option. This should be reverted back to proper a
107 * `InputInterface::isInteractive()` call as soon as we bump dependencies
108 * to Symfony\Console 3.x in Behat 4.x.
110 private function interactionIsNotSupported()
112 return $this->input->hasParameterOption('--no-interaction');