Ejemplo n.º 1
0
 /**
  * @param   InputInterface            $input  An InputInterface instance
  * @param   OutputInterface           $output An OutputInterface instance
  * @param   CollectionFinderInterface $finder The finder
  * @param   string                    $entity The entity name
  *
  * @return  void
  */
 protected function doIt(InputInterface $input, OutputInterface $output, $finder, $entity)
 {
     $count = 0;
     $force = $input->getOption('no-interaction');
     $repository = $this->repositoryFactory->forEntity($entity);
     $idAccessorRegistry = $this->repositoryFactory->getIdAccessorRegistry();
     foreach ($this->getRecords($finder) as $record) {
         $id = $idAccessorRegistry->getEntityId($record);
         $choice = 'no';
         if (!$force) {
             $question = new Question("Delete {$entity} #{$id} (yes,No,all)? ", 'no');
             $question->setAutocompleterValues(['yes', 'no', 'all']);
             $choice = $this->ask($input, $output, $question);
             if ($choice == 'all') {
                 $force = true;
             }
         }
         if ($force || $choice == 'yes') {
             $repository->remove($record);
             $count++;
         }
     }
     $repository->commit();
     $this->writeln($output, "Deleted {$count} {$entity} item(s).");
 }
Ejemplo n.º 2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $em = $this->getContainer()->get('doctrine')->getManager();
     $helper = $this->getHelper('question');
     $output->writeln("\n<question>                                      ");
     $output->writeln(' Welcome to the Fbeen slug generator. ');
     $output->writeln("                                      </question>\n");
     $entityName = $input->getArgument('entity');
     if (!$entityName) {
         $output->writeln('This command helps you to update slugs on an entire table.');
         $output->writeln('First, you need to give the entity for which you want to generate the slugs.');
         $output->writeln("\nYou must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.\n");
         $question = new Question('<info>The Entity shortcut name: </info>');
         $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateEntityName'));
         $autocompleter = new EntitiesAutoCompleter($em);
         $autocompleteEntities = $autocompleter->getSuggestions();
         $question->setAutocompleterValues($autocompleteEntities);
         $entityName = $helper->ask($input, $output, $question);
     }
     $entities = $em->getRepository($entityName)->findAll();
     $question = new ConfirmationQuestion('<info>Continue generating slugs for ' . $entityName . '</info> [<comment>no</comment>]? ', false);
     if (!$helper->ask($input, $output, $question)) {
         return;
     }
     $output->writeln("\nGenerating the slugs...");
     $slugupdater = new SlugUpdater();
     foreach ($entities as $entity) {
         $slugupdater->preUpdate(new LifecycleEventArgs($entity, $em));
         $em->flush();
     }
     $output->writeln("\nDone!\n");
 }
 /**
  * {@inheritdoc}
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     // Start question helper
     $questionHelper = $this->getQuestionHelper();
     $questionHelper->writeSection($output, 'Welcome to the united CRUD generator!');
     // get entity
     $entity = $input->getOption('entity');
     $question = new Question($questionHelper->getQuestion('Entity', $entity), $entity);
     $question->setValidator(function ($answer) {
         return Validators::validateEntityName($answer);
     });
     $complete = new EntitiesAutoCompleter($this->getContainer()->get('doctrine')->getManager());
     $completeEntities = $complete->getSuggestions();
     $question->setAutocompleterValues($completeEntities);
     $entity = $questionHelper->ask($input, $output, $question);
     $input->setOption('entity', $entity);
     // get bundle
     $destinationBundle = $input->getOption('bundle');
     $question = new Question($questionHelper->getQuestion('Destination bundle', $destinationBundle), $destinationBundle);
     $question->setValidator(function ($answer) {
         return Validators::validateBundleName($answer);
     });
     $question->setAutocompleterValues($this->getBundleSuggestions());
     $destinationBundle = $questionHelper->ask($input, $output, $question);
     $input->setOption('bundle', $destinationBundle);
 }
 /**
  * Asks for the namespace and sets it on the InputInterface as the 'namespace' option, if this option is not set yet.
  *
  * @param array $text What you want printed before the namespace is asked.
  *
  * @return string The namespace. But it's also been set on the InputInterface.
  */
 public function askForNamespace(array $text = null)
 {
     $namespace = $this->input->hasOption('namespace') ? $this->input->getOption('namespace') : null;
     // When the Namespace is filled in return it immediately if valid.
     try {
         if (!is_null($namespace) && !empty($namespace)) {
             Validators::validateBundleNamespace($namespace);
             return $namespace;
         }
     } catch (\Exception $error) {
         $this->writeError(array("Namespace '{$namespace}' is incorrect. Please provide a correct value.", $error->getMessage()));
         exit;
     }
     $ownBundles = $this->getOwnBundles();
     if (count($ownBundles) <= 0) {
         $this->writeError("Looks like you don't have created a bundle for your project, create one first.", true);
     }
     $namespace = '';
     // If we only have 1 or more bundles, we can prefill it.
     if (count($ownBundles) > 0) {
         $namespace = $ownBundles[1]['namespace'] . '/' . $ownBundles[1]['name'];
     }
     $namespaces = $this->getNamespaceAutoComplete($this->kernel);
     if (!is_null($text) && count($text) > 0) {
         $this->output->writeln($text);
     }
     $question = new Question($this->questionHelper->getQuestion('Bundle Namespace', $namespace), $namespace);
     $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateBundleNamespace'));
     $question->setAutocompleterValues($namespaces);
     $namespace = $this->questionHelper->ask($this->input, $this->output, $question);
     if ($this->input->hasOption('namespace')) {
         $this->input->setOption('namespace', $namespace);
     }
     return $namespace;
 }
Ejemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     if (null !== $this->getContainer()->getParameter('installed')) {
         throw new ApplicationInstalledException();
     }
     $currencies = Intl::getCurrencyBundle()->getCurrencyNames();
     $locales = Intl::getLocaleBundle()->getLocaleNames();
     $localeQuestion = new Question('<question>Please enter a locale:</question> ');
     $localeQuestion->setAutocompleterValues($locales);
     $currencyQuestion = new Question('<question>Please enter a currency:</question> ');
     $currencyQuestion->setAutocompleterValues($currencies);
     $passwordQuestion = new Question('<question>Please enter a password for the admin account:</question> ');
     $passwordQuestion->setHidden(true);
     $options = array('database-user' => new Question('<question>Please enter your database user name:</question> '), 'admin-username' => new Question('<question>Please enter a username for the admin account:</question> '), 'admin-password' => $passwordQuestion, 'admin-email' => new Question('<question>Please enter an email address for the admin account:</question> '), 'locale' => $localeQuestion, 'currency' => $currencyQuestion);
     /** @var QuestionHelper $dialog */
     $dialog = $this->getHelper('question');
     /** @var Question $question */
     foreach ($options as $option => $question) {
         if (null === $input->getOption($option)) {
             $value = null;
             while (empty($value)) {
                 $value = $dialog->ask($input, $output, $question);
                 if ($values = $question->getAutocompleterValues()) {
                     $value = array_search($value, $values);
                 }
             }
             $input->setOption($option, $value);
         }
     }
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getQuestionHelper();
     $questionHelper->writeSection($output, 'Welcome to the Doctrine2 CRUD generator');
     // namespace
     $output->writeln(array('', 'This command helps you generate CRUD controllers and templates.', '', 'First, you need to give the entity for which you want to generate a CRUD.', 'You can give an entity that does not exist yet and the wizard will help', 'you defining it.', '', 'You must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.', ''));
     if ($input->hasArgument('entity') && $input->getArgument('entity') != '') {
         $input->setOption('entity', $input->getArgument('entity'));
     }
     $question = new Question($questionHelper->getQuestion('The Entity shortcut name', $input->getOption('entity')), $input->getOption('entity'));
     $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateEntityName'));
     $autocompleter = new EntitiesAutoCompleter($this->getContainer()->get('doctrine')->getManager());
     $autocompleteEntities = $autocompleter->getSuggestions();
     $question->setAutocompleterValues($autocompleteEntities);
     $entity = $questionHelper->ask($input, $output, $question);
     $input->setOption('entity', $entity);
     list($bundle, $entity) = $this->parseShortcutNotation($entity);
     // write?
     $withWrite = 'yes';
     $input->setOption('with-write', $withWrite);
     // format
     $format = 'annotation';
     $input->setOption('format', $format);
     // route prefix
     $prefix = $this->getRoutePrefix($input, $entity);
     $output->writeln(array('', 'Determine the routes prefix (all the routes will be "mounted" under this', 'prefix: /prefix/, /prefix/new, ...).', ''));
     $prefix = $questionHelper->ask($input, $output, new Question($questionHelper->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix));
     $input->setOption('route-prefix', $prefix);
     // summary
     $output->writeln(array('', $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true), '', sprintf("You are going to generate a CRUD controller for \"<info>%s:%s</info>\"", $bundle, $entity), sprintf("using the \"<info>%s</info>\" format.", $format), ''));
 }
Ejemplo n.º 7
0
 /**
  * Asks a question and validates the response.
  *
  * @param  string   $question  The question
  * @param  array    $choices   Autocomplete options
  * @param  function $validator The callback function
  * @param  mixed    $default   The default value
  * @return string
  */
 public function askAndValidate($question, array $choices, $validator, $default = null)
 {
     $question = new Question($question, $default);
     if (count($choices)) {
         $question->setAutocompleterValues($choices);
     }
     $question->setValidator($validator);
     return $this->output->askQuestion($question);
 }
Ejemplo n.º 8
0
 /**
  * Configures the interactive part of the console application
  * @param InputInterface $input The console input object
  * @param OutputInterface $output The console output object
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     if (empty($input->getArgument('issue-key'))) {
         $this->connect($input->getOption('url'), $input->getOption('auth'));
         $question = new Question('Issue key: ');
         $question->setAutocompleterValues(Project::getInstance()->getAllProjectKeys());
         $input->setArgument('issue-key', $this->getHelper('question')->ask($input, $output, $question));
     }
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getQuestionHelper();
     $questionHelper->writeSection($output, 'Welcome to the Doctrine2 CRUD generator');
     // namespace
     $output->writeln(array('', 'This command helps you generate CRUD controllers and templates.', '', 'First, give the name of the existing entity for which you want to generate a CRUD', '(use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>)', ''));
     if ($input->hasArgument('entity') && $input->getArgument('entity') != '') {
         $input->setOption('entity', $input->getArgument('entity'));
     }
     $question = new Question($questionHelper->getQuestion('The Entity shortcut name', $input->getOption('entity')), $input->getOption('entity'));
     $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateEntityName'));
     $autocompleter = new EntitiesAutoCompleter($this->getContainer()->get('doctrine')->getManager());
     $autocompleteEntities = $autocompleter->getSuggestions();
     $question->setAutocompleterValues($autocompleteEntities);
     $entity = $questionHelper->ask($input, $output, $question);
     $input->setOption('entity', $entity);
     list($bundle, $entity) = $this->parseShortcutNotation($entity);
     try {
         $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle) . '\\' . $entity;
         $metadata = $this->getEntityMetadata($entityClass);
     } catch (\Exception $e) {
         throw new \RuntimeException(sprintf('Entity "%s" does not exist in the "%s" bundle. You may have mistyped the bundle name or maybe the entity doesn\'t exist yet (create it first with the "doctrine:generate:entity" command).', $entity, $bundle));
     }
     // write?
     $withWrite = $input->getOption('with-write') ?: false;
     $output->writeln(array('', 'By default, the generator creates two actions: list and show.', 'You can also ask it to generate "write" actions: new, update, and delete.', ''));
     $question = new ConfirmationQuestion($questionHelper->getQuestion('Do you want to generate the "write" actions', $withWrite ? 'yes' : 'no', '?', $withWrite), $withWrite);
     $withWrite = $questionHelper->ask($input, $output, $question);
     $input->setOption('with-write', $withWrite);
     // format
     $format = $input->getOption('format');
     $output->writeln(array('', 'Determine the format to use for the generated CRUD.', ''));
     $question = new Question($questionHelper->getQuestion('Configuration format (yml, xml, php, or annotation)', $format), $format);
     $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateFormat'));
     $format = $questionHelper->ask($input, $output, $question);
     $input->setOption('format', $format);
     // route prefix
     $prefix = $this->getRoutePrefix($input, $entity);
     $output->writeln(array('', 'Determine the routes prefix (all the routes will be "mounted" under this', 'prefix: /prefix/, /prefix/new, ...).', ''));
     $prefix = $questionHelper->ask($input, $output, new Question($questionHelper->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix));
     $input->setOption('route-prefix', $prefix);
     // controller folder?
     $controllerFolder = $input->getOption('controller-folder') ?: 'src/AppBundle/Controller/';
     $output->writeln(array('', 'By default, the generator creates the controller on Controller namespace.', 'You can also generate it on an subnamespace (Ex: src/AppBundle/Controller/Backend).', ''));
     $question = new Question($questionHelper->getQuestion('Determine the subnamespace you want:', $controllerFolder), $controllerFolder);
     $controllerFolder = $questionHelper->ask($input, $output, $question);
     if ($controllerFolder == 'src/AppBundle/Controller/') {
         $controllerFolder = '';
     }
     $input->setOption('controller-folder', $controllerFolder);
     // summary
     $output->writeln(array('', $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true), '', sprintf('You are going to generate a CRUD controller for "<info>%s:%s</info>"', $bundle, $entity), sprintf('using the "<info>%s</info>" format.', $format), ''));
 }
Ejemplo n.º 10
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     $output->write(_("Connecting to the Database..."));
     try {
         $db = \FreePBX::Database();
     } catch (\Exception $e) {
         $output->writeln("<error>" . _("Unable to connect to database!") . "</error>");
         return;
     }
     $output->writeln(_("Connected"));
     $driver = $db->getAttribute(\PDO::ATTR_DRIVER_NAME);
     $bundles = array();
     while (true) {
         $question = new Question($driver . '>', '');
         $question->setAutocompleterValues($bundles);
         $answer = $helper->ask($input, $output, $question);
         if (preg_match("/^exit/i", $answer)) {
             exit;
         }
         $bundles[] = $answer;
         try {
             $time_start = microtime(true);
             $ob = $db->query($answer);
             $time_end = microtime(true);
         } catch (\Exception $e) {
             $output->writeln("<error>" . $e->getMessage() . "</error>");
             continue;
         }
         if (!$ob) {
             $output->writeln("<error>" . $db->errorInfo() . "</error>");
             continue;
         }
         //if we get rows back from a query fetch them
         if ($ob->rowCount()) {
             $gotRows = $ob->fetchAll(\PDO::FETCH_ASSOC);
         } else {
             $gotRows = array();
         }
         if (!empty($gotRows)) {
             $rows = array();
             foreach ($gotRows as $row) {
                 $rows[] = array_values($row);
             }
             $table = new Table($output);
             $table->setHeaders(array_keys($gotRows[0]))->setRows($rows);
             $table->render();
             $output->writeln(sprintf(_("%s rows in set (%s sec)"), $ob->rowCount(), round($time_end - $time_start, 2)));
         } else {
             $output->writeln(_("Successfully executed"));
         }
     }
 }
Ejemplo n.º 11
0
 /**
  * Gets the question object that is to be asked.
  *
  * The question will either be a ChoiceQuestion, ConfirmationQuestion, or regular Question based on the configuration.
  *
  * @return \Symfony\Component\Console\Question\Question The question to be asked.
  */
 protected function _getQuestion()
 {
     if ($this->_isSelect()) {
         return new ChoiceQuestion($this->_displayQuestion(), $this->_choices, $this->_default);
     }
     if ($this->_isConfirmation()) {
         return new ConfirmationQuestion($this->_displayQuestion(), $this->_default);
     }
     $question = new Question($this->_displayQuestion(), $this->_default);
     $question->setAutocompleterValues($this->_choices);
     return $question;
 }
Ejemplo n.º 12
0
 /**
  * Asks a question and validates the response.
  *
  * @param string $question
  * @param array $choices
  * @param callback $validator
  * @param mixed $default
  * @param bool $secret
  *
  * @return string
  */
 public function askAndValidate($question, array $choices, $validator, $default = null, $secret = false)
 {
     $question = new Question($question, $default);
     if ($secret) {
         $question->setHidden(true);
     }
     if (count($choices)) {
         $question->setAutocompleterValues($choices);
     }
     $question->setValidator($validator);
     return $this->getOutput()->askQuestion($question);
 }
Ejemplo n.º 13
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $rootDir = realpath($this->getContainer()->getParameter('kernel.root_dir') . '/..');
     $entities = [];
     $files = glob($rootDir . '/src/AppBundle/Entity/*.php');
     foreach ($files as $file) {
         $entities[] = str_replace('/', '\\', str_replace('.php', '', str_replace($rootDir . '/src/', '', $file)));
     }
     $helper = $this->getHelper('question');
     $question = new Question('<info>Entity name (fully namespace)</info> (ex AppBundle\\Entity\\Post): ');
     $question->setAutocompleterValues($entities);
     $entityName = $helper->ask($input, $output, $question);
     if (empty($entityName)) {
         $output->writeln('<error>Entity name is required</error>');
         return;
     }
     $default = str_replace('\\Entity\\', '\\Form\\', $entityName) . 'Type';
     $question = new Question('<info>Entity name (fully namespace)</info> [' . $default . ']: ', $default);
     $formType = $helper->ask($input, $output, $question);
     $tokens = explode('\\', $entityName);
     $default = end($tokens) . 's';
     $question = new Question('<info>Controller name (without Controller suffix)</info> [' . $default . ']: ', $default);
     $controllerName = $helper->ask($input, $output, $question);
     $default = strtolower($controllerName);
     $question = new Question('<info>Controller route prefix</info> [' . $default . ']: ', $default);
     $routePrefix = $helper->ask($input, $output, $question);
     $default = preg_replace("/[^\\w\\d\\s]/", "_", $routePrefix);
     $question = new Question('<info>Route name prefix</info> [' . $default . ']: ', $default);
     $routeNamePrefix = $helper->ask($input, $output, $question);
     $default = $routePrefix;
     $question = new Question('<info>Template path</info> [' . $default . ']: ', $default);
     $templatePath = $helper->ask($input, $output, $question);
     $params = ['entityName' => $entityName, 'formType' => $formType, 'controllerName' => $controllerName, 'routePrefix' => $routePrefix, 'routeNamePrefix' => $routeNamePrefix, 'templatePath' => $templatePath];
     $builder = new \Mangati\BaseBundle\Builder\CrudControllerBuilder();
     $classContent = $builder->controller($params);
     $filename = $rootDir . '/src/AppBundle/Controller/' . $controllerName . 'Controller.php';
     file_put_contents($filename, $classContent);
     $output->writeln('<info>Generated controller class in </info>' . $filename);
     $baseDir = $rootDir . '/app/Resources/views/' . $templatePath;
     if (!is_dir($baseDir)) {
         mkdir($baseDir, 0777, true);
     }
     $indexTemplate = $builder->indexTemplate($params);
     $filename = $baseDir . '/index.html.twig';
     file_put_contents($filename, $indexTemplate);
     $output->writeln('<info>Generated index template in </info>' . $filename);
     $editTemplate = $builder->editTemplate($params);
     $filename = $baseDir . '/edit.html.twig';
     file_put_contents($filename, $editTemplate);
     $output->writeln('<info>Generated edit template in </info>' . $filename);
 }
Ejemplo n.º 14
0
 public function interact(InputInterface $input, OutputInterface $output)
 {
     $bundle = $input->getArgument('bundle');
     $name = $input->getArgument('name');
     if (null !== $bundle && null !== $name) {
         return;
     }
     $questionHelper = $this->getQuestionHelper();
     $questionHelper->writeSection($output, 'Welcome to the Symfony command generator');
     // bundle
     if (null !== $bundle) {
         $output->writeln(sprintf('Bundle name: %s', $bundle));
     } else {
         $output->writeln(array('', 'First, you need to give the name of the bundle where the command will', 'be generated (e.g. <comment>AppBundle</comment>)', ''));
         $bundleNames = array_keys($this->getContainer()->get('kernel')->getBundles());
         $question = new Question($questionHelper->getQuestion('Bundle name', $bundle), $bundle);
         $question->setAutocompleterValues($bundleNames);
         $question->setValidator(function ($answer) use($bundleNames) {
             if (!in_array($answer, $bundleNames)) {
                 throw new \RuntimeException(sprintf('Bundle "%s" does not exist.', $answer));
             }
             return $answer;
         });
         $question->setMaxAttempts(self::MAX_ATTEMPTS);
         $bundle = $questionHelper->ask($input, $output, $question);
         $input->setArgument('bundle', $bundle);
     }
     // command name
     if (null !== $name) {
         $output->writeln(sprintf('Command name: %s', $name));
     } else {
         $output->writeln(array('', 'Now, provide the name of the command as you type it in the console', '(e.g. <comment>app:my-command</comment>)', ''));
         $question = new Question($questionHelper->getQuestion('Command name', $name), $name);
         $question->setValidator(function ($answer) {
             if (empty($answer)) {
                 throw new \RuntimeException('The command name cannot be empty.');
             }
             return $answer;
         });
         $question->setMaxAttempts(self::MAX_ATTEMPTS);
         $name = $questionHelper->ask($input, $output, $question);
         $input->setArgument('name', $name);
     }
     // summary and confirmation
     $output->writeln(array('', $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg-white', true), '', sprintf('You are going to generate a <info>%s</info> command inside <info>%s</info> bundle.', $name, $bundle)));
     $question = new Question($questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true);
     if (!$questionHelper->ask($input, $output, $question)) {
         $output->writeln('<error>Command aborted</error>');
         return 1;
     }
 }
Ejemplo n.º 15
0
 /**
  * @param QuestionInterface $question
  * @return ChoiceQuestion|Question
  */
 public function create(QuestionInterface $question)
 {
     if ($question instanceof ChoiceQuestionInterface) {
         $consoleQuestion = new ChoiceQuestion($question->getQuestion(), $question->getChoiceArray(), $question->getDefaultAnswer());
     } else {
         $consoleQuestion = new Question($question->getQuestion(), $question->getDefaultAnswer());
     }
     if ($question->getErrorMessage() !== null) {
         $consoleQuestion->setErrorMessage($question->getErrorMessage());
     }
     if ($question->getAutocompleterValues() !== null) {
         $consoleQuestion->setAutocompleterValues($question->getAutocompleterValues());
     }
     return $consoleQuestion;
 }
Ejemplo n.º 16
0
 private function askForUrl($helper, $input, $output)
 {
     $controller = strtolower($input->getArgument('controller'));
     $action = strtolower($input->getArgument('action'));
     $bundles = array($controller, '/' . $controller, $action, '/' . $action);
     $question = new Question('<fg=yellow>Enter route url: </>', '');
     $question->setAutocompleterValues($bundles);
     $question->setValidator(function ($answer) {
         if ('/' !== substr($answer, 0, 1)) {
             throw new \RuntimeException('The route may start with "/"');
         }
         return $answer;
     });
     $question->setMaxAttempts(3);
     return $helper->ask($input, $output, $question);
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getQuestionHelper();
     if (!$input->getOption('no-summary')) {
         $questionHelper->writeSection($output, 'Welcome to the Sylius form generator');
         $output->writeln(array('', 'This command helps you generate Sylius forms.', '', 'First, you need to give the entity name to generate form.', 'You must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.', ''));
     }
     $bundleNames = $this->getContainer()->get('kernel')->getBundles();
     $bundleList = array();
     foreach ($bundleNames as $bundle) {
         if ($bundle instanceof AbstractResourceBundle) {
             $bundleList[] = $bundle->getName();
         }
     }
     while (true) {
         $question = new Question($questionHelper->getQuestion('The Entity shortcut name', $input->getOption('entity')), $input->getOption('entity'));
         $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateEntityName'));
         $question->setAutocompleterValues($bundleList);
         $entity = $input->getOption('entity');
         if (!$input->getOption('no-summary') || is_null($entity)) {
             $entity = $questionHelper->ask($input, $output, $question);
         }
         list($bundle, $entity) = $this->parseShortcutNotation($entity);
         // check reserved words
         if ($this->getGenerator()->isReservedKeyword($entity)) {
             $output->writeln(sprintf('<bg=red> "%s" is a reserved word</>.', $entity));
             $input->setOption('no-summary', null);
             continue;
         }
         try {
             $b = $this->getContainer()->get('kernel')->getBundle($bundle);
             $class = $this->getContainer()->get('doctrine')->getAliasNamespace($b->getName()) . '\\' . str_replace('\\', '/', $entity);
             if (class_exists($class)) {
                 break;
             }
             $output->writeln(sprintf('<bg=red>Entity "%s" does not exist.</>.', $entity));
         } catch (\Exception $e) {
             $output->writeln(sprintf('<bg=red>Bundle "%s" does not exist.</>', $bundle));
         }
         $input->setOption('no-summary', null);
     }
     $input->setOption('entity', $bundle . ':' . $entity);
 }
Ejemplo n.º 18
0
 /**
  * Returns the selected bundle.
  * If no bundle argument is set, the user will get ask for it.
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return BundleInterface
  */
 protected function getBundle(InputInterface $input, OutputInterface $output)
 {
     $kernel = $this->getContainer()->get('kernel');
     if ($input->hasArgument('bundle') && '@' === substr($input->getArgument('bundle'), 0, 1)) {
         return $kernel->getBundle(substr($input->getArgument('bundle'), 1));
     }
     $bundleNames = array_keys($kernel->getBundles());
     do {
         $question = '<info>Select the bundle</info>: ';
         $question = new Question($question);
         $question->setAutocompleterValues($bundleNames);
         $bundleName = $this->getHelperSet()->get('question')->ask($input, $output, $question);
         if (in_array($bundleName, $bundleNames)) {
             break;
         }
         $output->writeln(sprintf('<bg=red>Bundle "%s" does not exist.</bg>', $bundleName));
     } while (true);
     return $kernel->getBundle($bundleName);
 }
Ejemplo n.º 19
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     $accessTokenService = new AccessTokenService($this->getSlim());
     $accessTokenService->fetchTokens();
     $clientIds = [];
     foreach ($accessTokenService->getCursor() as $document) {
         $clientIds[] = $document->getClientId();
     }
     $question = new Question('Please enter the the client ID of the token you wish to delete: ');
     $question->setAutocompleterValues($clientIds);
     $clientId = $helper->ask($input, $output, $question);
     $question = new ConfirmationQuestion('Are you sure (y/n): ', false);
     if (!$helper->ask($input, $output, $question)) {
         return;
     }
     $accessTokenService->deleteToken($clientId);
     $output->writeln('<info>Supertoken successfully deleted!</info>');
 }
 public function addQuoption($name, $shortcut, $mode, $description, $default = null, $completions = [], $prompt = null)
 {
     $this->addOption($name, $shortcut, $mode, $description);
     if (!$prompt) {
         $prompt = $description;
     }
     if ($default) {
         $prompt = sprintf('%1$s (default = %2$s): ', $prompt, $default);
     } else {
         $prompt = sprintf('%1$s : ', $prompt);
     }
     if ($default) {
         $completions[] = $default;
     }
     $question = new Question($prompt, $default);
     $question->setAutocompleterValues($completions);
     $this->options[$name] = $default;
     $this->questions[$name] = $question;
     return $this;
 }
Ejemplo n.º 21
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('<info>Welcome to Console Client for PurePHP server.</info>');
     $pure = new Client($input->getOption('port'), $input->getOption('host'));
     $language = new ExpressionLanguage();
     $auto = ['pure', 'pure.map', 'pure.queue', 'pure.stack', 'pure.priority', 'pure.delete', 'pure.ping', 'exit'];
     $helper = $this->getHelper('question');
     $question = new Question('> ', '');
     do {
         $question->setAutocompleterValues($auto);
         $command = $helper->ask($input, $output, $question);
         $auto[] = $command;
         if ('exit' === $command) {
             break;
         }
         try {
             $result = $language->evaluate($command, ['pure' => $pure]);
             var_dump($result);
         } catch (\Exception $e) {
             $output->writeln('<error>' . get_class($e) . ": \n" . $e->getMessage() . '</error>');
         }
     } while (true);
 }
Ejemplo n.º 22
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $container = $this->getContainer();
     /** @var  $logger */
     $logger = $container->get('logger');
     $restaurante = $input->getArgument('restaurante');
     $ficheiro = $input->getOption('ficheiro');
     $em = $container->get('doctrine')->getManager();
     if (empty($restaurante)) {
         $restaurantes = $em->getRepository('EnquisaBundle:Restaurante')->findAll();
         $helper = $this->getHelper('question');
         $question = new Question('Nome do restaurante: ');
         $question->setAutocompleterValues($this->restaurantesToArray($restaurantes));
         $restaurante = $helper->ask($input, $output, $question);
     }
     $logger->info('Restaurante: ' . $restaurante);
     $resultado = $em->getRepository('EnquisaBundle:Restaurante')->findByNome($restaurante);
     if (count($resultado) !== 1) {
         throw new Exception('Restaurante non recoñecido');
     }
     $scanner = $container->get('scanner');
     // Pasar o path completo ao ficheiro
     $scanner->run($resultado[0], $ficheiro);
 }
 private function addFields(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper)
 {
     $fields = $this->parseFields($input->getOption('fields'));
     $output->writeln(array('', 'Instead of starting with a blank entity, you can add some fields now.', 'Note that the primary key will be added automatically (named <comment>id</comment>).', ''));
     $output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $output->writeln('');
         }
         $count += strlen($type);
         $output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $output->write(', ');
         } else {
             $output->write('.');
         }
     }
     $output->writeln('');
     $fieldValidator = function ($type) use($types) {
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     $boolValidator = function ($value) {
         if (null === ($valueAsBool = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE))) {
             throw new \InvalidArgumentException(sprintf('Invalid bool value "%s".', $value));
         }
         return $valueAsBool;
     };
     $precisionValidator = function ($precision) {
         if (!$precision) {
             return $precision;
         }
         $result = filter_var($precision, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 65)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid precision "%s".', $precision));
         }
         return $precision;
     };
     $scaleValidator = function ($scale) {
         if (!$scale) {
             return $scale;
         }
         $result = filter_var($scale, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 30)));
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid scale "%s".', $scale));
         }
         return $scale;
     };
     while (true) {
         $output->writeln('');
         $generator = $this->getGenerator();
         $question = new Question($questionHelper->getQuestion('New field name (press <return> to stop adding fields)', null), null);
         $question->setValidator(function ($name) use($fields, $generator) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             // check reserved words
             if ($generator->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a reserved word.', $name));
             }
             // check for valid PHP variable name
             if (!is_null($name) && !$generator->isValidPhpVariableName($name)) {
                 throw new \InvalidArgumentException(sprintf('"%s" is not a valid PHP variable name.', $name));
             }
             return $name;
         });
         $columnName = $questionHelper->ask($input, $output, $question);
         if (!$columnName) {
             break;
         }
         $defaultType = 'string';
         // try to guess the type by the column name prefix/suffix
         if (substr($columnName, -3) == '_at') {
             $defaultType = 'datetime';
         } elseif (substr($columnName, -3) == '_id') {
             $defaultType = 'integer';
         } elseif (substr($columnName, 0, 3) == 'is_') {
             $defaultType = 'boolean';
         } elseif (substr($columnName, 0, 4) == 'has_') {
             $defaultType = 'boolean';
         }
         $question = new Question($questionHelper->getQuestion('Field type', $defaultType), $defaultType);
         $question->setValidator($fieldValidator);
         $question->setAutocompleterValues($types);
         $type = $questionHelper->ask($input, $output, $question);
         $data = array('columnName' => $columnName, 'fieldName' => lcfirst(Container::camelize($columnName)), 'type' => $type);
         if ($type == 'string') {
             $question = new Question($questionHelper->getQuestion('Field length', 255), 255);
             $question->setValidator($lengthValidator);
             $data['length'] = $questionHelper->ask($input, $output, $question);
         } elseif ('decimal' === $type) {
             // 10 is the default value given in \Doctrine\DBAL\Schema\Column::$_precision
             $question = new Question($questionHelper->getQuestion('Precision', 10), 10);
             $question->setValidator($precisionValidator);
             $data['precision'] = $questionHelper->ask($input, $output, $question);
             // 0 is the default value given in \Doctrine\DBAL\Schema\Column::$_scale
             $question = new Question($questionHelper->getQuestion('Scale', 0), 0);
             $question->setValidator($scaleValidator);
             $data['scale'] = $questionHelper->ask($input, $output, $question);
         }
         $question = new Question($questionHelper->getQuestion('Is nullable', 'false'), false);
         $question->setValidator($boolValidator);
         $question->setAutocompleterValues(array('true', 'false'));
         if ($nullable = $questionHelper->ask($input, $output, $question)) {
             $data['nullable'] = $nullable;
         }
         $question = new Question($questionHelper->getQuestion('Unique', 'false'), false);
         $question->setValidator($boolValidator);
         $question->setAutocompleterValues(array('true', 'false'));
         if ($unique = $questionHelper->ask($input, $output, $question)) {
             $data['unique'] = $unique;
         }
         $fields[$columnName] = $data;
     }
     return $fields;
 }
Ejemplo n.º 24
0
 public function testAskWithAutocomplete()
 {
     if (!$this->hasSttyAvailable()) {
         $this->markTestSkipped('`stty` is required to test autocomplete functionality');
     }
     // Acm<NEWLINE>
     // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
     // <NEWLINE>
     // <UP ARROW><UP ARROW><NEWLINE>
     // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
     // <DOWN ARROW><NEWLINE>
     // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
     // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
     $inputStream = $this->getInputStream("Acm\nAcs\tTest\n\n\n\tTest\n\nS\nF00oo\t\n");
     $dialog = new QuestionHelper();
     $dialog->setInputStream($inputStream);
     $helperSet = new HelperSet(array(new FormatterHelper()));
     $dialog->setHelperSet($helperSet);
     $question = new Question('Please select a bundle', 'FrameworkBundle');
     $question->setAutocompleterValues(array('AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle'));
     $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('AsseticBundleTest', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('FrameworkBundle', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('SecurityBundle', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('FooBundleTest', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('AsseticBundle', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
     $this->assertEquals('FooBundle', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
 }
Ejemplo n.º 25
0
 /**
  * Interactively ask user to add field to his new Entity.
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  * @param QuestionHelper  $questionHelper
  *
  * @return $fields
  */
 private function addFields(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper)
 {
     $fields = $this->parseFields($input->getOption('fields'));
     $output->writeln(['', 'Instead of starting with a blank entity, you can add some fields now.', 'Note that the primary key will be added automatically (named <comment>id</comment>).', '']);
     $output->write('<info>Available types:</info> ');
     $types = array_keys(Type::getTypesMap());
     $count = 20;
     foreach ($types as $i => $type) {
         if ($count > 50) {
             $count = 0;
             $output->writeln('');
         }
         $count += strlen($type);
         $output->write(sprintf('<comment>%s</comment>', $type));
         if (count($types) != $i + 1) {
             $output->write(', ');
         } else {
             $output->write('.');
         }
     }
     $output->writeln('');
     $fieldValidator = function ($type) use($types) {
         if (!in_array($type, $types)) {
             throw new \InvalidArgumentException(sprintf('Invalid type "%s".', $type));
         }
         return $type;
     };
     $lengthValidator = function ($length) {
         if (!$length) {
             return $length;
         }
         $result = filter_var($length, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
         if (false === $result) {
             throw new \InvalidArgumentException(sprintf('Invalid length "%s".', $length));
         }
         return $length;
     };
     while (true) {
         $output->writeln('');
         $generator = $this->getEntityGenerator();
         $question = new Question($questionHelper->getQuestion('New field name (press <return> to stop adding fields)', null));
         $question->setValidator(function ($name) use($fields, $generator) {
             if (isset($fields[$name]) || 'id' == $name) {
                 throw new \InvalidArgumentException(sprintf('Field "%s" is already defined.', $name));
             }
             // check reserved words by database
             if ($generator->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a reserved word.', $name));
             }
             // check reserved words by victoire
             if ($this->isReservedKeyword($name)) {
                 throw new \InvalidArgumentException(sprintf('Name "%s" is a Victoire reserved word.', $name));
             }
             return $name;
         });
         $columnName = $questionHelper->ask($input, $output, $question);
         if (!$columnName) {
             break;
         }
         $defaultType = 'string';
         // try to guess the type by the column name prefix/suffix
         if (substr($columnName, -3) == '_at') {
             $defaultType = 'datetime';
         } elseif (substr($columnName, -3) == '_id') {
             $defaultType = 'integer';
         } elseif (substr($columnName, 0, 3) == 'is_') {
             $defaultType = 'boolean';
         } elseif (substr($columnName, 0, 4) == 'has_') {
             $defaultType = 'boolean';
         }
         $question = new Question($questionHelper->getQuestion('Field type', $defaultType), $defaultType);
         $question->setValidator($fieldValidator);
         $question->setAutocompleterValues($types);
         $type = $questionHelper->ask($input, $output, $question);
         $data = ['columnName' => $columnName, 'fieldName' => lcfirst(Container::camelize($columnName)), 'type' => $type];
         if ($type == 'string') {
             $question = new Question($questionHelper->getQuestion('Field length', 255), 255);
             $question->setValidator($lengthValidator);
             $data['length'] = $questionHelper->ask($input, $output, $question);
         }
         $fields[$columnName] = $data;
     }
     return $fields;
 }
 /**
  * Asks a question to the user.
  *
  * @param \Symfony\Component\Console\Input\InputInterface $input
  *   Input instance.
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  *   Output instance.
  * @param string $question_text
  *   The text of the question.
  * @param string $default_value
  *   Default value for the question.
  * @param array $suggestions
  *   (optional) Autocomplete values.
  *
  * @return string
  *   The user answer.
  */
 protected function ask(InputInterface $input, OutputInterface $output, $question_text, $default_value, $suggestions)
 {
     /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
     $helper = $this->getHelper('question');
     $question_text = "<info>{$question_text}</info>";
     if ($default_value) {
         $question_text .= " [<comment>{$default_value}</comment>]";
     }
     $question_text .= ': ';
     if ($default_value == 'yes' || $default_value == 'no') {
         $question = new ConfirmationQuestion($question_text, $default_value == 'yes');
     } else {
         $question = new Question($question_text, $default_value);
     }
     if ($suggestions) {
         $question->setAutocompleterValues($suggestions);
     }
     $answer = $helper->ask($input, $output, $question);
     return $answer;
 }
Ejemplo n.º 27
0
 /**
  * Prompt the user for input with auto completion.
  *
  * @param  string $question
  * @param  array  $choices
  * @param  string $default
  * @return string
  */
 public function askWithCompletion($question, array $choices, $default = null)
 {
     $helper = $this->getHelperSet()->get('question');
     $question = new Question("<question>{$question}</question>", $default);
     $question->setAutocompleterValues($choices);
     return $helper->ask($this->input, $this->output, $question);
 }
Ejemplo n.º 28
0
 private function getPackagesInteractively(IOInterface $io, InputInterface $input, OutputInterface $output, Composer $composer, array $packages)
 {
     if (!$input->isInteractive()) {
         throw new \InvalidArgumentException('--interactive cannot be used in non-interactive terminals.');
     }
     $requires = array_merge($composer->getPackage()->getRequires(), $composer->getPackage()->getDevRequires());
     $autocompleterValues = array();
     foreach ($requires as $require) {
         $autocompleterValues[strtolower($require->getTarget())] = $require->getTarget();
     }
     $installedPackages = $composer->getRepositoryManager()->getLocalRepository()->getPackages();
     foreach ($installedPackages as $package) {
         $autocompleterValues[$package->getName()] = $package->getPrettyName();
     }
     $helper = $this->getHelper('question');
     $question = new Question('<comment>Enter package name: </comment>', null);
     $io->writeError('<info>Press enter without value to end submission</info>');
     do {
         $autocompleterValues = array_diff($autocompleterValues, $packages);
         $question->setAutocompleterValues($autocompleterValues);
         $addedPackage = $helper->ask($input, $output, $question);
         if (!is_string($addedPackage) || empty($addedPackage)) {
             break;
         }
         $addedPackage = strtolower($addedPackage);
         if (!in_array($addedPackage, $packages)) {
             $packages[] = $addedPackage;
         }
     } while (true);
     $packages = array_filter($packages);
     if (!$packages) {
         throw new \InvalidArgumentException('You must enter minimum one package.');
     }
     $table = new Table($output);
     $table->setHeaders(array('Selected packages'));
     foreach ($packages as $package) {
         $table->addRow(array($package));
     }
     $table->render();
     if ($io->askConfirmation(sprintf('Would you like to continue and update the above package%s [<comment>yes</comment>]? ', 1 === count($packages) ? '' : 's'), true)) {
         return $packages;
     }
     throw new \RuntimeException('Installation aborted.');
 }
Ejemplo n.º 29
0
 protected function executeCommands(InputInterface $input, OutputInterface $output, $I, $bootstrap)
 {
     $dialog = new QuestionHelper();
     if (file_exists($bootstrap)) {
         require $bootstrap;
     }
     do {
         $question = new Question("<comment>\$I-></comment>");
         $question->setAutocompleterValues($this->actions);
         $command = $dialog->ask($input, $output, $question);
         if ($command == 'actions') {
             $output->writeln("<info>" . implode(' ', $this->actions));
             continue;
         }
         if ($command == 'exit') {
             return;
         }
         if ($command == '') {
             continue;
         }
         try {
             $value = eval("return \$I->{$command};");
             if ($value && !is_object($value)) {
                 codecept_debug($value);
             }
         } catch (\PHPUnit_Framework_AssertionFailedError $fail) {
             $output->writeln("<error>fail</error> " . $fail->getMessage());
         } catch (\Exception $e) {
             $output->writeln("<error>error</error> " . $e->getMessage());
         }
     } while (true);
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getQuestionHelper();
     // namespace
     $output->writeln(array('Bienvenue sur le générateur de CRUD de ceya !', '', 'Pour commencer, merci d\'indiquer sur qu\'elle entité ce base cette génération de CRUD', 'Vous pouvez utiliser la notation <comment>AppBundle:EntityName</comment>.', ''));
     if ($input->hasArgument('entity') && $input->getArgument('entity') != '') {
         $input->setOption('entity', $input->getArgument('entity'));
     }
     $question = new Question($questionHelper->getQuestion('Nom de votre entité', $input->getOption('entity')), $input->getOption('entity'));
     $question->setValidator(array('Ceya\\GeneratorBundle\\Command\\Validators', 'validateEntityName'));
     $autocompleter = new EntitiesAutoCompleter($this->getContainer()->get('doctrine')->getManager());
     $autocompleteEntities = $autocompleter->getSuggestions();
     $question->setAutocompleterValues($autocompleteEntities);
     $entity = $questionHelper->ask($input, $output, $question);
     $input->setOption('entity', $entity);
     list($bundle, $entity) = $this->parseShortcutNotation($entity);
     // route prefix
     $prefix = $this->getRoutePrefix($input, $entity);
     $output->writeln(array('', 'Déterminez le préfixage des routes. Exemple: /prefix/, /prefix/new, ...).', ''));
     $prefix = $questionHelper->ask($input, $output, new Question($questionHelper->getQuestion('Préfixe des routes', '/' . $prefix), '/' . $prefix));
     $input->setOption('route-prefix', $prefix);
     // summary
     $output->writeln(array('', sprintf("Vous allez générer un contrôleur CRUD pour \"<info>%s:%s</info>\"", $bundle, $entity), ''));
 }