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).");
 }
 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.º 3
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $login = $input->getArgument("login");
     $helper = $this->getHelper('question');
     $question = new Question("Unix password for « {$login} » : ");
     $question->setHidden(true);
     $question->setHiddenFallback(false);
     $password = $input->getArgument("password") ? $input->getArgument("password") : $helper->ask($input, $output, $question);
     $blih = new Blih($login, $password);
     $blihRepositoriesResponse = $blih->repository()->all();
     if ($blihRepositoriesResponse->code == 200) {
         $user = $this->getUserOrCreateIt($login);
         $repositoryNames = array_keys(get_object_vars($blihRepositoriesResponse->body->repositories));
         foreach ($repositoryNames as $repositoryName) {
             $output->writeln("> Repository « {$login}/{$repositoryName} »");
             $repository = $this->getRepoOrCreateIt($user, $repositoryName);
             $aclResponse = $blih->repository($repositoryName)->acl()->get();
             if ($aclResponse->code == 200) {
                 $acls = get_object_vars($aclResponse->body);
                 foreach ($acls as $aclLogin => $acl) {
                     $output->writeln("  ACL for « {$aclLogin} »: {$acl}");
                     $aclUser = $this->getUserOrCreateIt($aclLogin);
                     $repositoryACL = $this->getACLOrCreateIt($aclUser, $repository);
                     $repositoryACL->setR(strpos($acl, "r") !== false);
                     $repositoryACL->setW(strpos($acl, "w") !== false);
                     $repositoryACL->setA(strpos($acl, "a") !== false);
                     $this->getContainer()->get("doctrine")->getManager()->persist($repositoryACL);
                 }
             }
             $output->writeln("");
             $this->getContainer()->get("doctrine")->getManager()->persist($repository);
             $this->getContainer()->get("doctrine")->getManager()->flush();
         }
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($input->getOption("password")) {
         $password = $input->getOption("password");
     } else {
         $question = new Question('Password: '******'question');
         $password = $helper->ask($input, $output, $question);
     }
     $server = new Server\Database\Mysql();
     $server->setHostname($input->getArgument("host"));
     $server->setUser("provisioning");
     $server->setPassword($this->createPassword());
     $server->setDatabase("provisioning");
     $server->setMode($input->getArgument("mode"));
     $server->setType($input->getArgument("type"));
     $server->setActive(false);
     // convert errors to PDOExceptions
     $options = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
     $dsn = sprintf("mysql:host=%s;port=%s;charset=utf8", $server->getHostname(), 3306);
     $pdo = new \PDO($dsn, $input->getArgument("user"), $password, $options);
     $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
     $pdo->exec("SET NAMES utf8;");
     $pdo->exec("CREATE USER '{$server->getUser()}'@'%' IDENTIFIED BY '{$server->getPassword()}';");
     $pdo->exec("GRANT CREATE, DROP, GRANT OPTION, LOCK TABLES, REFERENCES, EVENT, ALTER, DELETE, INDEX, INSERT, SELECT, UPDATE, CREATE TEMPORARY TABLES, TRIGGER, CREATE VIEW, SHOW VIEW, ALTER ROUTINE, CREATE ROUTINE, EXECUTE, CREATE USER, PROCESS, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHOW DATABASES, USAGE ON *.* TO '{$server->getUser()}' WITH GRANT OPTION;");
     $pdo->exec("CREATE DATABASE {$server->getDatabase()} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;");
     // Write to DB
     $entityManager = $this->getProvisioningServer("mysql")->getEntityManager();
     $entityManager->persist($server);
     $entityManager->flush();
     $table = $this->getMySqlServersTable([$server], $output);
     $table->render();
 }
Ejemplo n.º 5
0
 /**
  * @return SimpleQuestion
  */
 private function buildAuthorQuestion()
 {
     $question = new SimpleQuestion('<question>Enter the author (name <*****@*****.**>):</question>');
     $question->setValidator($this->buildValidator());
     $question->setMaxAttempts(3);
     return $question;
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     if (trim($input->getOption('name')) == '') {
         $question = new Question\Question('Please enter the client name: ');
         $question->setValidator(function ($value) {
             if (trim($value) == '') {
                 throw new \Exception('The client name can not be empty');
             }
             $doctrine = $this->getContainer()->get('doctrine');
             $client = $doctrine->getRepository('AppBundle:Client')->findOneBy(['name' => $value]);
             if ($client instanceof \AppBundle\Entity\Client) {
                 throw new \Exception('The client name must be unique');
             }
             return $value;
         });
         $question->setMaxAttempts(5);
         $input->setOption('name', $helper->ask($input, $output, $question));
     }
     $grants = $input->getOption('grant-type');
     if (!(is_array($grants) && count($grants))) {
         $question = new Question\ChoiceQuestion('Please select the grant types (defaults to password and facebook_access_token): ', [\OAuth2\OAuth2::GRANT_TYPE_AUTH_CODE, \OAuth2\OAuth2::GRANT_TYPE_CLIENT_CREDENTIALS, \OAuth2\OAuth2::GRANT_TYPE_EXTENSIONS, \OAuth2\OAuth2::GRANT_TYPE_IMPLICIT, \OAuth2\OAuth2::GRANT_TYPE_REFRESH_TOKEN, \OAuth2\OAuth2::GRANT_TYPE_USER_CREDENTIALS, 'http://grants.api.schoolmanager.ledo.eu.org/facebook_access_token'], '5,6');
         $question->setMultiselect(true);
         $question->setMaxAttempts(5);
         $input->setOption('grant-type', $helper->ask($input, $output, $question));
     }
     parent::interact($input, $output);
 }
Ejemplo n.º 7
0
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     $username = $helper->ask($input, $output, new Question('Username: '******'Password: '******'Username: <info>' . $username . '</info>');
     $output->writeln('Roles:    <info>' . implode(', ', $roles) . '</info>');
     $this->showRoleWarnings($roles, $output);
     if (!$helper->ask($input, $output, new ConfirmationQuestion('Create user? [y/N]: ', false))) {
         return;
     }
     $provider = $this->getContainer()->get('orm.user_provider');
     $provider->createUser($username, $password, $roles);
     $output->writeln("Created new user");
 }
Ejemplo n.º 8
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     parent::bootstrapProcessWire($output);
     $name = $input->getArgument('name');
     $email = $input->getOption('email');
     $pass = $input->getOption('password');
     $roles = explode(",", $input->getOption('roles'));
     $helper = $this->getHelper('question');
     if (!$email) {
         $question = new Question('Please enter a email address : ', 'email');
         $email = $helper->ask($input, $output, $question);
     }
     if (!$pass) {
         $question = new Question('Please enter a password : '******'password');
         $question->setHidden(true);
         $question->setHiddenFallback(false);
         $pass = $helper->ask($input, $output, $question);
     }
     if (!\ProcessWire\wire("pages")->get("name={$name}") instanceof \ProcessWire\NullPage) {
         $output->writeln("<error>User '{$name}' already exists!</error>");
         exit(1);
     }
     $user = $this->createUser($email, $name, $this->userContainer, $pass);
     $user->save();
     if ($input->getOption('roles')) {
         $this->attachRolesToUser($name, $roles, $output);
     }
     if ($pass) {
         $output->writeln("<info>User '{$name}' created successfully!</info>");
     } else {
         $output->writeln("<info>User '{$name}' created successfully! Please do not forget to set a password.</info>");
     }
 }
Ejemplo n.º 9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $username = $input->getArgument('username');
     $email = $input->getArgument('email');
     $repository = $this->getRepository();
     /* @var $entity User */
     $entity = $repository->createModel(array());
     try {
         $repository->findByUsername($username);
         $output->writeln(sprintf('A user with the username %s already exists.', $username));
         return 1;
     } catch (NotFound $e) {
     }
     $entity->setUsername($username);
     if ($email) {
         try {
             $repository->findByEmail($email);
             $output->writeln(sprintf('A user with the email %s already exists.', $email));
             return 1;
         } catch (NotFound $e) {
         }
         $entity->setEmail($username);
     }
     $questionHelper = new QuestionHelper();
     $question = new Question(sprintf('<question>%s</question>: ', 'Name (not required):'));
     $entity->setName($questionHelper->ask($input, $output, $question));
     $question = new Question(sprintf('<question>%s</question>: ', 'Enter a password:'******'User %s added successfully.', $username));
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getHelper('question');
     $question = new Question($this->getQuestion('Enter a comma separated list of the models you want to create the pivot table for', $input->getOption('models')), $input->getOption('models'));
     $question->setValidator(function ($answer) {
         $answer = array_map(function ($el) {
             return trim($el);
         }, explode(',', $answer));
         if (2 != count($answer)) {
             throw new \RuntimeException('This Option requires exactly 2 models');
         }
         return $answer;
     });
     $question->setMaxAttempts(3);
     $models = $questionHelper->ask($input, $output, $question);
     $table = $input->getOption('table');
     if (!$table) {
         $table = 'tl_' . strtolower($models[0]) . '_' . strtolower($models[1]);
     }
     $question = new Question($this->getQuestion('Enter the name of the table being created', $table), $table);
     $question->setValidator(function ($answer) {
         if ('tl_' !== substr($answer, 0, 3)) {
             throw new \RuntimeException('The name of the table should be prefixed with \'tl_\'');
         }
         return $answer;
     });
     $question->setMaxAttempts(3);
     $table = $questionHelper->ask($input, $output, $question);
     $question = new Question($this->getQuestion('Enter the relative path to your contao bundle', './src'), './src');
     $base = $questionHelper->ask($input, $output, $question);
     $this->parameters = ['models' => $models, 'table' => $table, 'base' => $base];
 }
Ejemplo n.º 11
0
 /**
  * @inheritdoc
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $secret = $input->getArgument('secret');
     if (empty($secret)) {
         /** @var QuestionHelper $dialog */
         $helper = $this->getHelper('question');
         $question = new Question('<question>The secret to share</question>: ');
         $secret = $helper->ask($input, $output, $question);
         $question = new Question('<question>Number of shared secrets to create</question> <comment>[3]</comment>: ', 3);
         $question->setValidator(function ($a) {
             if (!is_int($a) && !ctype_digit($a)) {
                 throw new \Exception('The number of shared secrets must be an integer');
             }
             return (int) $a;
         });
         $shares = $helper->ask($input, $output, $question);
         $question = new Question('<question>Number of shared secrets required</question> <comment>[2]</comment>: ', 2);
         $question->setValidator(function ($a) {
             if (!is_int($a) && !ctype_digit($a)) {
                 throw new \Exception('The number of shared secrets required must be an integer');
             }
             return (int) $a;
         });
         $threshold = $helper->ask($input, $output, $question);
     } else {
         $shares = $input->getOption('shares');
         $threshold = $input->getOption('threshold');
     }
     $shared = Secret::share($secret, $shares, $threshold);
     /** @var FormatterHelper $formatter */
     $formatter = $this->getHelper('formatter');
     $block = $formatter->formatBlock($shared, 'info', true);
     $output->writeln($block);
 }
 /**
  * Execute the command
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $db = $input->getOption('db');
     if (empty($db)) {
         throw new \InvalidArgumentException('You must define the database name with --db');
     }
     $password = $input->getOption('password');
     if (is_null($password)) {
         $helper = $this->getHelper('question');
         $question = new Question('Password: '******'host'), $input->getOption('user'), $password);
     } catch (\Exception $e) {
         throw new \RuntimeException("Can't connect to the database. Check your credentials");
     }
     $writer = new \Inet\Neuralyzer\Configuration\Writer();
     $ignoreFields = $input->getOption('ignore-field');
     $writer->protectCols($input->getOption('protect'));
     // Override the protection if fields are defined
     if (!empty($ignoreFields)) {
         $writer->protectCols(true);
         $writer->setProtectedCols($ignoreFields);
     }
     $writer->setIgnoredTables($input->getOption('ignore-table'));
     $data = $writer->generateConfFromDB($pdo, new \Inet\Neuralyzer\Guesser());
     $writer->save($data, $input->getOption('file'));
     $output->writeln('<comment>Configuration written to ' . $input->getOption('file') . '</comment>');
 }
Ejemplo n.º 13
0
 public function handle(InputInterface $input, OutputInterface $output)
 {
     $data = [];
     $helper = $this->command->getHelper('question');
     $data['jiraHost'] = $helper->ask($input, $output, new Question('Domain (yourdomain.atlassian.net): ', false));
     $data['jiraUser'] = $helper->ask($input, $output, new Question('Username: '******'Password: '******'Confirm Password: '******'Password cannot be blank');
     //        }
     //
     //        if ($password !== $password2) {
     //            throw new \RuntimeException('Passwords must match.');
     //        }
     $data['jiraPassword'] = $password;
     if ($this->config->write($data) !== false) {
         $output->writeln('Config written to file: ' . $this->config->filePath());
     } else {
         $output->writeln('Nothing written..');
     }
 }
Ejemplo n.º 14
0
 /**
  *
  * TODO Provide extensibility to list of Sugar 7 boxes (allow hard coding, usage of a web service, etc.)
  * {inheritDoc}
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $box = $input->getArgument('box');
     if (empty($box)) {
         $output->writeln('You MUST provide a <info>Vagrant Box Name</info> for your Sugar instance.');
         $output->writeln('<comment>You may pick one from below OR provide your own.</comment>');
         $table = new Table($output);
         $table->setHeaders(array('Box Name', 'PHP', 'Apache', 'MySQL', 'Elasticsearch', 'OS'));
         $table->addRow(['mmarum/sugar7-php54', '5.4.x', '2.2.x', '5.5.x', '1.4.x', 'Ubuntu 12.04']);
         $table->addRow(['mmarum/sugar7-php53', '5.3.x', '2.2.x', '5.5.x', '1.4.x', 'Ubuntu 12.04']);
         $table->render();
         $helper = $this->getHelper('question');
         $question = new Question('<info>Name of Vagrant Box?</info> <comment>[mmarum/sugar7-php54]</comment> ', 'mmarum/sugar7-php54');
         $question->setValidator(function ($answer) {
             if (empty($answer)) {
                 throw new \RuntimeException('You must provide a Box Name to continue!');
             }
             return $answer;
         });
         $question->setMaxAttempts(2);
         $box = $helper->ask($input, $output, $question);
         $input->setArgument('box', $box);
     }
     $output->writeln("<info>Using {$box} ...</info>");
 }
 /**
  * @see Command
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questions = array();
     if (!$input->getArgument('username')) {
         $question = new Question('Please give the username:'******'Username can not be empty');
             }
             return $username;
         });
         $questions['username'] = $question;
     }
     if (!$input->getArgument('password')) {
         $question = new Question('Please enter the new password:'******'Password can not be empty');
             }
             return $password;
         });
         $question->setHidden(true);
         $questions['password'] = $question;
     }
     foreach ($questions as $name => $question) {
         $answer = $this->getHelper('question')->ask($input, $output, $question);
         $input->setArgument($name, $answer);
     }
 }
Ejemplo n.º 16
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     $question = new Question('Please enter app\'s shared secret: ');
     $question->setValidator(function ($answer) {
         if (empty($answer)) {
             throw new RuntimeException('Shared secret must be provided');
         }
         return $answer;
     });
     $question->setHidden(true);
     $question->setMaxAttempts(2);
     $sharedSecret = $helper->ask($input, $output, $question);
     $receiptFile = __DIR__ . '/../../../tmp/receipt';
     if (!is_file(realpath($receiptFile))) {
         throw new RuntimeException(sprintf('Create a file with receipt data here %s', $receiptFile));
     }
     $receiptData = file_get_contents($receiptFile);
     if (empty($receiptData)) {
         throw new RuntimeException(sprintf('Put receipt data here %s', $receiptFile));
     }
     $validator = new Validator();
     $validator->setSecret($sharedSecret);
     $validator->setReceiptData($receiptData);
     $response = $validator->validate();
     var_dump($response);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($input->getOption("password")) {
         $password = $input->getOption("password");
     } else {
         $question = new Question('Password: '******'question');
         $password = $helper->ask($input, $output, $question);
     }
     $server = new Server\Database\Redshift();
     $server->setHostname($input->getArgument("host"));
     $server->setConnectionId($input->getArgument("connectionId"));
     $server->setUser($input->getArgument("user"));
     $server->setPassword($password);
     $server->setDatabase($input->getArgument("database"));
     $server->setMode("active");
     $server->setActive(false);
     // Write to DB
     $entityManager = $this->getProvisioningServer("redshift")->getEntityManager();
     $entityManager->persist($server);
     $entityManager->flush();
     $table = $this->getRedshiftServersTable([$server], $output);
     $table->render();
 }
Ejemplo n.º 18
0
 /**
  * @return SimpleQuestion
  */
 private function buildQuestion()
 {
     $question = new SimpleQuestion('<question>Enter your project homepage:</question>');
     $question->setValidator($this->buildValidator());
     $question->setMaxAttempts(3);
     return $question;
 }
Ejemplo n.º 19
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $number = $input->getOption('number');
     $debug = true;
     try {
         // Create a instance of Registration class.
         $r = new \Registration($number, $debug);
         $r->codeRequest('sms');
         // could be 'voice' too
     } catch (\Exception $e) {
         $output->writeln('<error>the number is invalid ' . $number . '</error>');
         return false;
     }
     $helper = $this->getHelper('question');
     $question = new Question('Digite seu código de confirmação recebido por SMS (sem hífen "-"): ', false);
     $question->setValidator(function ($value) use($output, $r) {
         try {
             $response = $r->codeRegister($value);
             $output->writeln('<fg=green>Your password is: ' . $response->pw . ' and your login: '******'</>');
         } catch (\Exception $e) {
             $output->writeln("<error>Código inválido, tente novamente mais tarde!</error>");
             return false;
         }
         return true;
     });
     $codigo = $helper->ask($input, $output, $question);
     $output->writeln('<fg=green>Your number is ' . $number . ' and your code: ' . $codigo . '</>');
 }
 /**
  * {@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);
 }
Ejemplo n.º 21
0
 protected function allServers(Environment $environment, InputInterface $input, OutputInterface $output, \Closure $action)
 {
     //Loop on the servers
     /**
      * @var \Onigoetz\Deployer\Configuration\Server
      */
     foreach ($environment->getServers() as $server) {
         $output->writeln("Deploying on <info>{$server->getHost()}</info>");
         $output->writeln('-------------------------------------------------');
         //Ask server password if needed ?
         if (!($password = $server->getPassword())) {
             $text = "Password for <info>{$server->getUsername()}@{$server->getHost()}</info>:";
             $question = new Question($text, false);
             $question->setHidden(true)->setHiddenFallback(false);
             $password = $this->getHelper('question')->ask($input, $output, $question);
         }
         //Login to server
         $ssh = new Net_SFTP($server->getHost());
         if (!$ssh->login($server->getUsername(), $password)) {
             throw new \Exception("Login failed on host '{$server->getHost()}'");
         }
         $action($ssh);
         $ssh->disconnect();
     }
 }
Ejemplo n.º 22
0
 /**
  * Prompt user to fill in a value
  *
  * @param InputInterface $input
  * @param OutputInterface $output
  * @param $label    string          The description of the value
  * @param $default  string|array    The default value. If array given, question will be multiple-choice and the first item will be default. Can also be empty.
  * @param bool $required
  * @param bool $hidden  Hide user input (useful for passwords)
  *
  * @return string   Answer
  */
 protected function _ask(InputInterface $input, OutputInterface $output, $label, $default = '', $required = false, $hidden = false)
 {
     $helper = $this->getHelper('question');
     $text = $label;
     if (is_array($default)) {
         $defaultValue = $default[0];
     } else {
         $defaultValue = $default;
     }
     if (!empty($defaultValue)) {
         $text .= ' [default: <info>' . $defaultValue . '</info>]';
     }
     $text .= ': ';
     if (is_array($default)) {
         $question = new Question\ChoiceQuestion($text, $default, 0);
     } else {
         $question = new Question\Question($text, $default);
     }
     if ($hidden === true) {
         $question->setHidden(true);
     }
     $answer = $helper->ask($input, $output, $question);
     if ($required && empty($answer)) {
         return $this->_ask($input, $output, $label, $default, $hidden);
     }
     return $answer;
 }
Ejemplo n.º 23
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     $question = new Question('Choose the status for the account [0=Consumer, 1=Administrator]: ');
     $question->setValidator(function ($value) {
         if (preg_match('/^0|1$/', $value)) {
             return $value;
         } else {
             throw new \Exception('Status must be either 0 or 1');
         }
     });
     $status = $helper->ask($input, $output, $question);
     $question = new Question('Enter the username of the account: ');
     $question->setValidator(function ($value) {
         if (!preg_match('/^[A-z0-9\\-\\_\\.]{3,32}$/', $value)) {
             throw new \Exception('The username must match the following regexp [A-z0-9\\-\\_\\.]{3,32}');
         }
         return $value;
     });
     $userName = $helper->ask($input, $output, $question);
     $password = sha1(mcrypt_create_iv(40));
     $this->userTable->create(array('status' => $status, 'name' => $userName, 'password' => \password_hash($password, PASSWORD_DEFAULT), 'date' => new DateTime()));
     $output->writeln('Created user ' . $userName . ' successful');
     $output->writeln('The following passord was assigned to the account:');
     $output->writeln($password);
 }
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     /** @var QuestionHelper $questionHelper */
     $questionHelper = $this->getHelper('question');
     if ($input->getArgument('state') === null) {
         $output->writeln('<info>State required</info>');
         $question = new ChoiceQuestion('<question>Select state</question>', ['new', 'used', 'future'], 'new');
         $state = $questionHelper->ask($input, $output, $question);
         $input->setArgument('state', $state);
     }
     if ($input->getArgument('year') === null) {
         $output->writeln('<info>Year required</info>');
         $question = new Question('<question>Enter year:</question> ', 1990);
         $question->setValidator(function ($answer) {
             if ($answer < 1990) {
                 throw new \RuntimeException('Year has to be bigger then 1990');
             }
             return $answer;
         });
         $year = $questionHelper->ask($input, $output, $question);
         $input->setArgument('year', $year);
     }
     $style = new OutputFormatterStyle('black', 'white', ['bold', 'underscore']);
     $output->getFormatter()->setStyle('thanks', $style);
     $output->writeln('<thanks>Thanks!</thanks>');
 }
Ejemplo n.º 25
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);
         }
     }
 }
Ejemplo n.º 26
0
 /**
  * @param $dialog
  * @param null $default
  * @return mixed
  */
 protected function useSymfonyQuestion($dialog, $default = null, $validation)
 {
     $question = new Question($dialog . ' ', $default);
     $question->setValidator($validation);
     $helper = $this->getHelper('question');
     return $helper->ask($this->input, $this->output, $question);
 }
Ejemplo n.º 27
0
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     if ($input->hasOption("browse") && $input->getOption("browse")) {
         # print the status list
         $command = $this->getApplication()->find('status');
         $statusInput = new ArrayInput(array(), $command->getDefinition());
         $command->run($statusInput, $output);
         # ask with boxes to handle
         $helper = $this->getHelper('question');
         $question = new Question('<fg=yellow>' . "Select box/boxes to " . $this->action . ':</> ', null);
         $question->setMaxAttempts(5);
         # set up validation for the question
         $question->setValidator(function ($answer) {
             $vagrant = new Vagrant();
             # check if the answer can be resolved
             if (!count($vagrant->resolveStr($answer))) {
                 throw new \RuntimeException('Your selection does not match any boxes');
             }
             return $answer;
         });
         # if we have an answer, set it as an argument, and move on
         if ($answer = $helper->ask($input, $output, $question)) {
             $input->setArgument("identifier", $answer);
         }
     }
 }
Ejemplo n.º 28
0
 /**
  * Informs the display about the structure of a Field.
  * 
  * Each time the Field structure changes for some reason, this method shall
  * be called.
  *
  * @param \Feeld\Display\DisplayDataSourceInterface $field
  * @throws Exception
  */
 public function informAboutStructure(\Feeld\Display\DisplayDataSourceInterface $field)
 {
     parent::informAboutStructure($field);
     $this->field = $field;
     if ($field instanceof \Feeld\Field\Entry) {
         $this->symfonyQuestion = new SymfonyQuestion((string) $this, $field instanceof DefaultValueInterface && $field->hasDefault() ? $field->getDefault() : null);
     } elseif ($field instanceof \Feeld\Field\Select) {
         $this->symfonyQuestion = new \Symfony\Component\Console\Question\ChoiceQuestion((string) $this, array_keys($field->getOptions()), $field instanceof DefaultValueInterface && $field->hasDefault() ? $field->getDefault() : null);
         if ($field instanceof \Feeld\Field\CommonProperties\MultipleChoiceInterface && $field->isMultipleChoice()) {
             $field->symfonyQuestion->setMultiselect(true);
         }
     } elseif ($field instanceof \Feeld\Field\CloakedEntry) {
         $this->symfonyQuestion = new SymfonyQuestion((string) $this, $field instanceof DefaultValueInterface && $field->hasDefault() ? $field->getDefault() : null);
         $this->symfonyQuestion->setHidden(true);
     } elseif ($field instanceof \Feeld\Field\Constant) {
         throw new Exception('Constants are currently not supported in SymfonyConsoleDisplay');
     } elseif ($field instanceof \Feeld\Field\Checkbox) {
         $this->symfonyQuestion = new \Symfony\Component\Console\Question\ConfirmationQuestion((string) $this, $field instanceof DefaultValueInterface && $field->hasDefault() ? $field->getDefault() : true, '/^' . strtolower(substr($this->getTrueOption(), 0, 1)) . '/i');
     }
     $this->symfonyQuestion->setNormalizer(function ($value) {
         return $this->field->getSanitizer()->filter($value);
     });
     $this->symfonyQuestion->setValidator(function ($value) {
         $validationResultSet = $this->field->validateValue($value);
         if ($validationResultSet->hasErrors()) {
             $this->field->clearValidationResult();
             throw new \Exception(implode(PHP_EOL, $validationResultSet->getErrorMessages()));
         }
         return $this->field->getFilteredValue();
     });
     $this->symfonyQuestion->setMaxAttempts(null);
 }
 /**
  * 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.º 30
0
 /**
  * {@inheritdoc}
  */
 public function interact(InputInterface $input, OutputInterface $output)
 {
     if (null !== $input->getOption('more-than-days') && null !== $input->getOption('less-than-days')) {
         throw new InvalidArgumentException('Options --more-than-days and --less-than-days cannot be used together.');
     }
     if (null === $input->getOption('more-than-days') && null === $input->getOption('less-than-days')) {
         $input->setOption('more-than-days', self::DEFAULT_MORE_THAN_DAYS);
     }
     $resourceFQCN = $input->hasArgument('entity') ? $input->getArgument('entity') : null;
     $isForced = $input->getOption('force');
     if (null !== $resourceFQCN && !class_exists($resourceFQCN)) {
         $errorCallback = function ($resourceFQCN) use($output) {
             $output->writeln('<info>Abort the purge operation. Nothing has been deleted from the database.</info>');
             throw new InvalidArgumentException(sprintf('Entity %s is not a valid fully qualified class name.', $resourceFQCN));
         };
         $output->writeln(sprintf('<info>"%s" is not a valid resource name.</info>', $resourceFQCN));
         if ($isForced) {
             $errorCallback($resourceFQCN);
         }
         $helper = $this->getHelper('question');
         $question = new Question('<question>Please insert a valid fully qualified class name: </question>');
         $question->setValidator(function ($answer) {
             if (!class_exists($answer)) {
                 throw new \RuntimeException('The fully qualified class name does not exist. Please choose a value from the table above.');
             }
             return $answer;
         });
         $question->setMaxAttempts(2);
         $resourceFQCN = $helper->ask($input, $output, $question);
         if (!$resourceFQCN) {
             $errorCallback($resourceFQCN);
         }
         $input->setArgument('entity', $resourceFQCN);
     }
 }