/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $schoolId = $input->getOption('schoolId'); if (!$schoolId) { $schoolTitles = []; foreach ($this->schoolManager->findBy([], ['title' => 'ASC']) as $school) { $schoolTitles[$school->getTitle()] = $school->getId(); } $helper = $this->getHelper('question'); $question = new ChoiceQuestion("What is this user's primary school?", array_keys($schoolTitles)); $question->setErrorMessage('School %s is invalid.'); $schoolTitle = $helper->ask($input, $output, $question); $schoolId = $schoolTitles[$schoolTitle]; } $school = $this->schoolManager->findOneBy(['id' => $schoolId]); if (!$school) { throw new \Exception("School with id {$schoolId} could not be found."); } $userRecord = ['firstName' => $input->getOption('firstName'), 'lastName' => $input->getOption('lastName'), 'email' => $input->getOption('email'), 'telephoneNumber' => $input->getOption('telephoneNumber'), 'campusId' => $input->getOption('campusId'), 'username' => $input->getOption('username'), 'password' => $input->getOption('password')]; $userRecord = $this->fillUserRecord($userRecord, $input, $output); $user = $this->userManager->findOneBy(['campusId' => $userRecord['campusId']]); if ($user) { throw new \Exception('User #' . $user->getId() . " with campus id {$userRecord['campusId']} already exists."); } $user = $this->userManager->findOneBy(['email' => $userRecord['email']]); if ($user) { throw new \Exception('User #' . $user->getId() . " with email address {$userRecord['email']} already exists."); } $table = new Table($output); $table->setHeaders(array('Campus ID', 'First', 'Last', 'Email', 'Username', 'Phone Number'))->setRows(array([$userRecord['campusId'], $userRecord['firstName'], $userRecord['lastName'], $userRecord['email'], $userRecord['username'], $userRecord['telephoneNumber']])); $table->render(); $helper = $this->getHelper('question'); $output->writeln(''); $question = new ConfirmationQuestion("<question>Do you wish to add this user to Ilios in {$school->getTitle()}?</question>\n", true); if ($helper->ask($input, $output, $question)) { $user = $this->userManager->create(); $user->setFirstName($userRecord['firstName']); $user->setLastName($userRecord['lastName']); $user->setEmail($userRecord['email']); $user->setCampusId($userRecord['campusId']); $user->setAddedViaIlios(true); $user->setEnabled(true); $user->setSchool($school); $user->setUserSyncIgnore(false); $this->userManager->update($user); $authentication = $this->authenticationManager->create(); $authentication->setUsername($userRecord['username']); $user->setAuthentication($authentication); $encodedPassword = $this->encoder->encodePassword($user, $userRecord['password']); $authentication->setPasswordBcrypt($encodedPassword); $this->authenticationManager->update($authentication); $output->writeln('<info>Success! New user #' . $user->getId() . ' ' . $user->getFirstAndLastName() . ' created.</info>'); } else { $output->writeln('<comment>Canceled.</comment>'); } }
/** * {@inheritdoc} */ protected function handle() { $plugins = elgg_get_plugins('inactive'); if (empty($plugins)) { system_message('All plugins are active'); return; } $ids = array_map(function (ElggPlugin $plugin) { return $plugin->getID(); }, $plugins); $ids = array_values($ids); if ($this->option('all')) { $activate_ids = $ids; } else { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select plugins you would like to activate (comma-separated list of indexes)', $ids); $question->setMultiselect(true); $activate_ids = $helper->ask($this->input, $this->output, $question); } if (empty($activate_ids)) { throw new \RuntimeException('You must select at least one plugin'); } $plugins = []; foreach ($activate_ids as $plugin_id) { $plugins[] = elgg_get_plugin_from_id($plugin_id); } do { $additional_plugins_activated = false; foreach ($plugins as $key => $plugin) { if ($plugin->isActive()) { unset($plugins[$key]); continue; } if (!$plugin->activate()) { // plugin could not be activated in this loop, maybe in the next loop continue; } $ids = array('cannot_start' . $plugin->getID(), 'invalid_and_deactivated_' . $plugin->getID()); foreach ($ids as $id) { elgg_delete_admin_notice($id); } // mark that something has changed in this loop $additional_plugins_activated = true; unset($plugins[$key]); system_message("Plugin {$plugin->getFriendlyName()} has been activated"); } if (!$additional_plugins_activated) { // no updates in this pass, break the loop break; } } while (count($plugins) > 0); if (count($plugins) > 0) { foreach ($plugins as $plugin) { $msg = $plugin->getError(); $string = $msg ? 'admin:plugins:activate:no_with_msg' : 'admin:plugins:activate:no'; register_error(elgg_echo($string, array($plugin->getFriendlyName()))); } } elgg_flush_caches(); }
/** * @param string $path * @param InputInterface $input * @param OutputInterface $output */ protected function binaryInstallWindows($path, InputInterface $input, OutputInterface $output) { $php = Engine::factory(); $table = new Table($output); $table->setRows([['<info>' . $php->getName() . ' Path</info>', $php->getPath()], ['<info>' . $php->getName() . ' Version</info>', $php->getVersion()], ['<info>Compiler</info>', $php->getCompiler()], ['<info>Architecture</info>', $php->getArchitecture()], ['<info>Thread safety</info>', $php->getZts() ? 'yes' : 'no'], ['<info>Extension dir</info>', $php->getExtensionDir()], ['<info>php.ini</info>', $php->getIniPath()]])->render(); $inst = Install::factory($path); $progress = $this->getHelperSet()->get('progress'); $inst->setProgress($progress); $inst->setInput($input); $inst->setOutput($output); $inst->install(); $deps_handler = new Windows\DependencyLib($php); $deps_handler->setProgress($progress); $deps_handler->setInput($input); $deps_handler->setOutput($output); $helper = $this->getHelperSet()->get('question'); $cb = function ($choices) use($helper, $input, $output) { $question = new ChoiceQuestion('Multiple choices found, please select the appropriate dependency package', $choices); $question->setMultiselect(false); return $helper->ask($input, $output, $question); }; foreach ($inst->getExtDllPaths() as $dll) { if (!$deps_handler->resolveForBin($dll, $cb)) { throw new \Exception('Failed to resolve dependencies'); } } }
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); }
/** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { /** @var StorageInterface $storage */ $storage = $this->getContainer()->get('storage'); $files = $input->getArgument('files'); if ($input->getOption('latest')) { $remoteFiles = $storage->remoteListing(); if (count($remoteFiles) > 0) { $files[] = end($remoteFiles); $input->setArgument('files', $files); } } if ($input->hasArgument('files') && !empty($files)) { return; } $remoteFiles = $storage->remoteListing(); $localFiles = $storage->localListing(); if (count(array_diff($remoteFiles, $localFiles)) === 0) { $output->writeln('All files fetched'); return; } $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Which backup', array_values(array_diff($remoteFiles, $localFiles))); $question->setMultiselect(true); $question->setErrorMessage('Backup %s is invalid.'); $question->setAutocompleterValues([]); $input->setArgument('files', $helper->ask($input, $output, $question)); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->setForce($input->getOption('force')); $this->setInput($input); $this->setOutput($output); $verbosityLevelMap = [LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL, LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL, LogLevel::DEBUG => OutputInterface::VERBOSITY_NORMAL]; $consoleLogger = new ConsoleLogger($output, $verbosityLevelMap); $this->getContainer()->get('claroline.manager.user_manager')->setLogger($consoleLogger); $helper = $this->getHelper('question'); //get excluding roles $roles = $this->getContainer()->get('claroline.persistence.object_manager')->getRepository('ClarolineCoreBundle:Role')->findAllPlatformRoles(); $roleNames = array_map(function ($role) { return $role->getName(); }, $roles); $roleNames[] = 'NONE'; $all = $input->getOption('all'); $questionString = $all ? 'Roles to exclude: ' : 'Roles to include: '; $question = new ChoiceQuestion($questionString, $roleNames); $question->setMultiselect(true); $roleNames = $helper->ask($input, $output, $question); $rolesSearch = array_filter($roles, function ($role) use($roleNames) { return in_array($role->getName(), $roleNames); }); $this->deleteUsers($all, $rolesSearch); }
protected function interact(InputInterface $input, OutputInterface $output) { $questionHelper = $this->getQuestionHelper(); $questionHelper->writeSection($output, 'Welcome to the Symfony2Admingenerator'); $output->writeln('<comment>Create an admingenerator bundle with generate:bundle</comment>'); $generator = $input->getOption('generator'); $question = new ChoiceQuestion('Generator to use (doctrine, doctrine_odm, propel)', array('doctrine', 'doctrine_odm', 'propel'), 0); $question->setErrorMessage('Generator to use have to be doctrine, doctrine_odm or propel.'); $generator = $questionHelper->ask($input, $output, $question); $input->setOption('generator', $generator); // Model name $modelName = $input->getOption('model-name'); $question = new Question($questionHelper->getQuestion('Model name', $modelName), $modelName); $question->setValidator(function ($answer) { if (empty($answer) || preg_match('#[^a-zA-Z0-9]#', $answer)) { throw new \RuntimeException('Model name should not contain any special characters nor spaces.'); } return $answer; }); $modelName = $questionHelper->ask($input, $output, $question); $input->setOption('model-name', $modelName); // prefix $prefix = $input->getOption('prefix'); $question = new Question($questionHelper->getQuestion('Prefix of yaml', $prefix), $prefix); $question->setValidator(function ($prefix) { if (!preg_match('/([a-z]+)/i', $prefix)) { throw new \RuntimeException('Prefix have to be a simple word'); } return $prefix; }); $prefix = $questionHelper->ask($input, $output, $question); $input->setOption('prefix', $prefix); parent::interact($input, $output); }
protected function showTasksToDelete(InputInterface $input, OutputInterface $output, $tasks) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select the task that you want to delete', $tasks->toArray(), 0); $question->setErrorMessage('Task %s does not exist.'); return $helper->ask($input, $output, $question); }
protected function interact(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $this->selectedSchema = $input->getArgument('name'); if (!array_key_exists($this->selectedSchema, $this->schemaList)) { $question = new ChoiceQuestion('Please select of of the following templates:', array_keys($this->schemaList)); $validator = function ($answer) use($output) { if (!array_key_exists($answer, $this->schemaList)) { throw new \RuntimeException('The name of the template not found'); } return $answer; }; $question->setValidator($validator); $question->setMaxAttempts(2); $this->selectedSchema = $helper->ask($input, $output, $question); } $schema = $this->schemaList[$this->selectedSchema]; foreach ($schema->getUndefinedVariables() as $var) { $question = new Question(sprintf('Please enter value for variable %s:', $var)); $answer = $helper->ask($input, $output, $question); $schema->setVariable($var, $answer); } $dir = $input->getOption('dir'); if (!$dir) { $dir = str_replace('\\', '/', $schema->getVariable('NAMESPACE')); } $this->selectedDir = trim($dir, '/\\'); }
public function testAskChoice() { $questionHelper = new SymfonyQuestionHelper(); $helperSet = new HelperSet(array(new FormatterHelper())); $questionHelper->setHelperSet($helperSet); $heroes = array('Superman', 'Batman', 'Spiderman'); $inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n"); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '2'); $question->setMaxAttempts(1); // first answer is an empty answer, we're supposed to receive the default value $this->assertEquals('Spiderman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('What is your favorite superhero? [Spiderman]', $output); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes); $question->setMaxAttempts(1); $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes); $question->setErrorMessage('Input "%s" is not a superhero!'); $question->setMaxAttempts(2); $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('Input "Fabien" is not a superhero!', $output); try { $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '1'); $question->setMaxAttempts(1); $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question); $this->fail(); } catch (\InvalidArgumentException $e) { $this->assertEquals('Value "Fabien" is invalid', $e->getMessage()); } $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, null); $question->setMaxAttempts(1); $question->setMultiselect(true); $this->assertEquals(array('Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question)); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0,1'); $question->setMaxAttempts(1); $question->setMultiselect(true); $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output); $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, ' 0 , 1 '); $question->setMaxAttempts(1); $question->setMultiselect(true); $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question)); $this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output); }
protected function interact(InputInterface $input, OutputInterface $output) { $instance = $input->getArgument('instance'); if (empty($instance)) { // find instances based on tag(s) $tags = $input->getOption('tag'); $tags = $this->convertTags($tags); $repository = new Repository(); $instanceCollection = $repository->findEc2InstancesByTags($tags); $count = count($instanceCollection); if ($count == 0) { throw new \Exception('No instance found matching the given tags'); } elseif ($count == 1) { $instanceObj = $instanceCollection->getFirst(); /* @var $instanceObj Instance */ $input->setArgument('instance', $instanceObj->getInstanceId()); } else { $mapping = []; // dynamically add current tags foreach (array_keys($tags) as $tagName) { $mapping[$tagName] = 'Tags[?Key==`' . $tagName . '`].Value | [0]'; } foreach ($input->getOption('column') as $tagName) { $mapping[$tagName] = 'Tags[?Key==`' . $tagName . '`].Value | [0]'; } $labels = []; foreach ($instanceCollection as $instanceObj) { /* @var $instanceObj Instance */ $instanceLabel = $instanceObj->getInstanceId(); $tmp = []; foreach ($instanceObj->extractData($mapping) as $field => $value) { if (!empty($value)) { $tmp[] = "{$field}: {$value}"; } } if (count($tmp)) { $labels[] = $instanceLabel . ' (' . implode('; ', $tmp) . ')'; } else { $labels[] = $instanceLabel; } } $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select an instance', $labels); $question->setErrorMessage('Instance %s is invalid.'); $instance = $helper->ask($input, $output, $question); $output->writeln('Selected Instance: ' . $instance); list($instance) = explode(' ', $instance); $input->setArgument('instance', $instance); } } if (!$input->getOption('force')) { $helper = $this->getHelper('question'); $question = new ConfirmationQuestion("Are you sure you want to terminate following instance? {$instance} [y/N] ", false); if (!$helper->ask($input, $output, $question)) { throw new \Exception('Operation aborted'); } $input->setOption('force', true); } }
/** * {@inheritdoc} */ protected function getChoiceQuestion() { // Translate the default into an array key. $defaultKey = $this->default !== null ? array_search($this->default, $this->options, true) : $this->default; $question = new ChoiceQuestion($this->name . " (enter a number to choose): ", $this->options, $defaultKey !== false ? $defaultKey : null); $question->setMaxAttempts($this->maxAttempts); return $question; }
public function __construct() { if (!$this->validate(App::get('in')->getOption('environment'))) { $question = new ChoiceQuestion('Do you want a development, test, or production environment?', ['development', 'test', 'production'], 'development'); $question->setErrorMessage('%s is invalid.'); $this->validate(App::get('io')->question($question)); } App::get('io')->write("<comment>environment:</> <info>{$this->environment}</>"); }
/** * Execute command * * @param InputInterface $input Input instance * @param OutputInterface $output Output instance * * @return int|null|void */ public function execute(InputInterface $input, OutputInterface $output) { $this->elevateProcess($input, $output); $pid = null; $grep = $input->getArgument('grep'); $command = new CommandBuilder('strace', '-f'); $command->setOutputRedirect(CommandBuilder::OUTPUT_REDIRECT_ALL_STDOUT); $output->writeln('<h2>Starting process stracing</h2>'); if (empty($pid)) { list($pidList, $processList) = $this->buildProcessList(); if ($input->getOption('all')) { $pid = 'all'; } else { try { $question = new ChoiceQuestion('Please choose process for tracing', $processList); $question->setMaxAttempts(1); $questionDialog = new QuestionHelper(); $pid = $questionDialog->ask($input, $output, $question); } catch (\InvalidArgumentException $e) { // Invalid value, just stop here throw new \CliTools\Exception\StopException(1); } } } if (!empty($pid)) { switch ($pid) { case 'all': $command->addArgumentTemplate('-p %s', implode(',', $pidList)); break; default: $command->addArgumentTemplate('-p %s', $pid); break; } // Stats if ($input->getOption('c')) { $command->addArgument('-c'); } // Relative time if ($input->getOption('r')) { $command->addArgument('-r'); } else { $command->addArgument('-tt'); } // System trace filter if ($input->getOption('e')) { $command->addArgumentTemplate('-e %s', $input->getOption('e')); } // Add grep if (!empty($grep)) { $grepCommand = new CommandBuilder('grep'); $grepCommand->addArgument('--color=auto')->addArgument($grep); $command->addPipeCommand($grepCommand); } $command->executeInteractive(); } return 0; }
public function choice($question, array $choices, $default = null, $multiple = false) { if (null !== $default) { $values = array_flip($choices); $default = $values[$default]; } $choiceQuestion = new ChoiceQuestion($question, $choices, $default); $choiceQuestion->setMultiselect($multiple); return $this->askQuestion($choiceQuestion); }
protected function getWebContainerNames($containers, InputInterface $input, OutputInterface $output) { # Prompt the user $helper = $this->getHelperSet()->get('question'); $containers[] = 'all'; $question = new ChoiceQuestion('<fg=cyan;bg=blue>Please select the numbers corresponding to which DrupalCI web environments to support. Separate multiple entries with commas. (Default: [0])</fg=cyan;bg=blue>', $containers, '0'); $question->setMultiselect(true); $results = $helper->ask($input, $output, $question); return $results; }
/** * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { // TODO: Ensure that configurations have been initialized // Get available config sets $helper = new ConfigHelper(); $configsets = $helper->getAllConfigSets(); $homedir = getenv('HOME'); // Check if passed argument is 'all' $names = $input->getArgument('setting'); if (empty($names)) { // If no argument passed, prompt the user for which config set to display $qhelper = $this->getHelper('question'); $message = "<question>Choose the number corresponding to which configuration set(s) to display:</question> "; $output->writeln($message); $message = "<comment>Separate multiple values with commas.</comment>"; $options = array_merge(array_keys($configsets), array('current', 'all')); $question = new ChoiceQuestion($message, $options, 0); $question->setMultiselect(TRUE); $names = $qhelper->ask($input, $output, $question); } if (in_array('all', $names)) { $names = array_keys($configsets); } // Is passed config set valid? foreach ($names as $key => $name) { if ($name == 'current') { $env_vars = $helper->getCurrentEnvVars(); $output->writeln("<info>---------------- Start config set: <options=bold>CURRENT DCI ENVIRONMENT</options=bold></info> ----------------</info>"); $output->writeln("<comment;options=bold>Defined in ~/.drupalci/config:</comment;options=bold>"); $contents = $helper->getCurrentConfigSetContents(); foreach ($contents as $line) { $parsed = explode("=", $line); if (!empty($parsed[0]) && !empty($parsed[1])) { $output->writeln("<comment>" . strtoupper($parsed[0]) . ": </comment><info>" . $parsed[1] . "</info>"); } } if (!empty($env_vars)) { $output->writeln("<comment;options=bold>Defined in Environment Variables:</comment;options=bold>"); foreach ($env_vars as $key => $value) { $output->writeln("<comment>" . strtoupper($key) . ": </comment><info>" . $value . "</info>"); } $output->writeln("<info>------------ End config set: <options=bold>CURRENT DCI ENVIRONMENT</options=bold></info> ----------------</info>"); $output->writeln(''); } } elseif (in_array($name, array_keys($configsets))) { $contents = file_get_contents($configsets[$name]); $output->writeln("<info>---------------- Start config set: <options=bold>{$name}</options=bold></info> ----------------</info>"); $output->writeln($contents); $output->writeln("<info>------------ End config set: <options=bold>{$name}</options=bold></info> ----------------</info>"); $output->writeln(''); } else { $output->writeln("<error>Configuration set '{$name}' not found. Skipping.</error>"); } } }
public function choice($question, $choices, $default = null, $errorMessage = null) { /** @var QuestionHelper $q */ $q = $this->getHelper('question'); if (!$question instanceof ChoiceQuestion) { $question = new ChoiceQuestion($question, $choices, $default); } if ($errorMessage !== null) { $question->setErrorMessage($errorMessage); } return $q->ask($this->in, $this->out, $question); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return */ protected function execute(InputInterface $input, OutputInterface $output) { // Busca todas tabelas do banco $getTables = array_map(function ($value) { return array_values($value)[0]; }, $this->get('db')->fetchAll('SHOW TABLES', array())); // Remove a tabela de usuário da lista $getTables = array_filter($getTables, function ($campo) { return $campo !== 'users'; }); if (count($getTables) === 0) { return $output->writeln('<error>Nenhuma tabela foi encontrada.</error>'); } if ($input->getOption('tables') === null) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Selecione as tabelas para gerar os padrões CRUD <comment>(pressione em branco para selecionar todas)</comment>', $getTables, implode(',', array_keys($getTables))); $question->setMultiselect(true); $tables_generate = $helper->ask($input, $output, $question); } else { $tables_in = explode(',', $input->getOption('tables')); $tables_generate = array(); foreach ($tables_in as $table_in) { if (in_array($table_in, $getTables)) { $tables_generate[] = $table_in; } } } if (count($tables_generate) === 0) { return $output->writeln('<error>Nenhuma tabela foi selecionada.</error>'); } $output->writeln('Você selecionou: <comment>' . implode('</comment>, <comment>', $tables_generate) . '</comment>'); $tables = array(); foreach ($tables_generate as $table_name) { if ($output->isVerbose()) { $output->writeln(sprintf('Capturando informações sobre a tabela <comment>"%s"</comment>', $table_name)); } $table_info = $this->getInfoTable($table_name, $input, $output); if (is_array($table_info)) { $tables[$table_name] = $table_info; } else { if ($output->isVerbose()) { $output->writeln(sprintf('<info>A tabela "%s" não será gerada.</info>', $table_name)); } } } $output->writeln('Aguarde estamos gerando...'); foreach ($tables as $table_name => $data) { $this->createController($table_name, $data, $input, $output); $this->createViews($table_name, $data, $input, $output); $this->createRoutes($table_name, $data, $input, $output); $this->createMenu($table_name, $data, $input, $output); } }
/** * Returns a generator selected by the user from a multilevel console menu. */ protected function selectGenerator(InputInterface $input, OutputInterface $output) { // Narrow menu tree according to the active menu items. $active_menu_tree = $this->menuTree; foreach ($this->activeMenuItems as $active_menu_item) { $active_menu_tree = $active_menu_tree[$active_menu_item]; } // The $active_menu_tree can be either an array of child menu items or // the TRUE value indicating that the user reached the final menu point and // active menu items contain the actual command name. if (is_array($active_menu_tree)) { $subtrees = $command_names = []; // We build $choices as an associative array to be able to find // later menu items by respective labels. foreach ($active_menu_tree as $menu_item => $subtree) { $menu_item_label = $this->createMenuItemLabel($menu_item, is_array($subtree)); if (is_array($subtree)) { $subtrees[$menu_item] = $menu_item_label; } else { $command_names[$menu_item] = $menu_item_label; } } asort($subtrees); asort($command_names); // Generally the choices array consists of the following parts: // - Reference to the parent menu level. // - Sorted list of nested menu levels. // - Sorted list of commands. $choices = ['..' => '..'] + $subtrees + $command_names; $question = new ChoiceQuestion('<title>Select generator:</title>', array_values($choices)); $question->setPrompt(' >>> '); $answer_label = $this->getHelper('question')->ask($input, $output, $question); $answer = array_search($answer_label, $choices); if (!$answer) { throw new \UnexpectedValueException(sprintf('"%s" menu item was not found', $answer_label)); } if ($answer == '..') { // Exit the application if the user choices zero key // on the top menu level. if (count($this->activeMenuItems) == 0) { return NULL; } // Set the menu one level higher. array_pop($this->activeMenuItems); } else { // Set the menu one level deeper. $this->activeMenuItems[] = $answer; } return $this->selectGenerator($input, $output); } else { return implode(':', $this->activeMenuItems); } }
/** * @param array $items An associative array of choices. * @param string $text Some text to precede the choices. * @param InputInterface $input * @param OutputInterface $output * @param mixed $default A default (as a key in $items). * * @throws \RuntimeException on failure * * @return mixed * The chosen item (as a key in $items). */ public function choose(array $items, $text = 'Enter a number to choose an item:', InputInterface $input, OutputInterface $output, $default = null) { $itemList = array_values($items); $defaultKey = $default !== null ? array_search($default, $itemList) : null; $question = new ChoiceQuestion($text, $itemList, $defaultKey); $question->setMaxAttempts(5); $choice = $this->ask($input, $output, $question); $choiceKey = array_search($choice, $items); if ($choiceKey === false) { throw new \RuntimeException("Invalid value: {$choice}"); } return $choiceKey; }
protected function interact(InputInterface $input, OutputInterface $output) { $profile = $input->getArgument('profile'); if (empty($profile)) { $profileManager = new Manager(); $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select the profile you want to use', $profileManager->listAllProfiles()); $question->setErrorMessage('Profile %s is invalid.'); $profile = $helper->ask($input, $output, $question); $output->writeln('Selected Profile: ' . $profile); $input->setArgument('profile', $profile); } }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var RestaurantRepository $restaurantRepository */ $restaurantRepository = $this->entityManager->getRepository('SlackOrder\\Entity\\Restaurant'); /** @var Restaurant $restaurant */ $restaurant = $restaurantRepository->findOneBy(['command' => $input->getArgument('commandName')]); if (null === $restaurant) { throw new \InvalidArgumentException('This command doesn\'t exists.'); } $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Witch field do you want to set ?', ['Token', 'Start hour', 'End hour', 'Phone number', 'Email', 'Name', 'Example', 'Sender email', 'Send order by email [0/1]'], 0); $question->setErrorMessage('Invalid field %s.'); $field = $helper->ask($input, $output, $question); $newValueQuestion = new Question(sprintf('The new value of %s : ', $field)); $newValue = $helper->ask($input, $output, $newValueQuestion); switch ($field) { case 'Token': $restaurant->setToken($newValue); break; case 'Start hour': $restaurant->setStartHour($newValue); break; case 'End hour': $restaurant->setEndHour($newValue); break; case 'Phone number': $restaurant->setPhoneNumber($newValue); break; case 'Email': $restaurant->setEmail($newValue); break; case 'Name': $restaurant->setName($newValue); break; case 'Url menu': $restaurant->setUrlMenu($newValue); break; case 'Example': $restaurant->setExample($newValue); break; case 'Sender email': $restaurant->setSenderEmail($newValue); break; case 'Send order by email [0/1]': $restaurant->setSendOrderByEmail($newValue); break; } $this->validateRestaurant($restaurant); $this->entityManager->persist($restaurant); $this->entityManager->flush(); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $template = $input->getArgument('template'); $directory = $input->getOption('directory'); $file = $input->getOption('filename'); if ($template === null) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select your project type (defaults to common):', $this->availableTemplates, 0); $question->setErrorMessage('Color %s is invalid.'); $template = $helper->ask($input, $output, $question); } $filePath = $this->initializer->initialize($template, $directory, $file); $output->writeln(sprintf('<comment>Successfully create deployer configuration: <info>%s</info></comment>', $filePath)); }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $config = ['email' => null, 'password' => null, 'user.agent' => null, 'proxy.http' => null]; // E-mail question $question = new Question('eRepublik account e-mail: '); $question->setValidator(function ($answer) { if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) { throw new \RuntimeException("This is not a valid e-mail address."); } return $answer; }); $question->setMaxAttempts(2); $config['email'] = $helper->ask($input, $output, $question); // Password question $question = new Question('eRepublik password: '******'password'] = $helper->ask($input, $output, $question); // User-Agent question $question = new Question('What User-Agent string to use (you can leave it empty): '); $config['user.agent'] = $helper->ask($input, $output, $question); // Type of proxy question $question = new ChoiceQuestion('What kind of proxy do you want to use: ', ['No proxy at all (default)', 'HTTP proxy']); $question->setMaxAttempts(2); $question->setErrorMessage('Proxy %s is invalid.'); $proxyType = $helper->ask($input, $output, $question); switch ($proxyType) { case 'HTTP proxy': $question = new Question('HTTP proxy (ip:port:username:password): '); $question->setValidator(function ($answer) { if (empty($answer)) { throw new \RuntimeException("Proxy cannot be empty."); } return $answer; }); $question->setMaxAttempts(2); $config['proxy.http'] = $helper->ask($input, $output, $question); break; } $configPath = $this->getApplication()->getConfigPath(); file_put_contents($configPath, json_encode($config)); $output->writeln('Config file has been written to ' . realpath($configPath)); }
public function askRoles($all, $input, $output, $container, $helper) { $roles = $container->get('claroline.persistence.object_manager')->getRepository('ClarolineCoreBundle:Role')->findAllPlatformRoles(); $roleNames = array_map(function ($role) { return $role->getName(); }, $roles); $roleNames[] = 'NONE'; $questionString = $all ? 'Roles to exclude: ' : 'Roles to include: '; $question = new ChoiceQuestion($questionString, $roleNames); $question->setMultiselect(true); $roleNames = $helper->ask($input, $output, $question); return array_filter($roles, function ($role) use($roleNames) { return in_array($role->getName(), $roleNames); }); }
/** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $templateList = $this->getTemplatesList($this->findTemplates()); $prettyTemplateList = $this->formatTemplatesList($templateList); $helper = $this->getHelper('question'); $question = new ChoiceQuestion('What kind of template, You would like to create?', $prettyTemplateList); $question->setErrorMessage('Template %s is invalid'); $selectedTemplate = $helper->ask($input, $output, $question); // find a key for selected template $key = array_search($selectedTemplate, $prettyTemplateList); $templateDirectoryName = $templateList[$key]; $targetPath = $input->getArgument(self::ARGUMENT_PATH_NAME); $this->createTemplate($templateDirectoryName, $targetPath); $output->writeln(sprintf('<comment>%s</comment> created into <info>%s</info>', $selectedTemplate, $targetPath)); }
protected function interactAskForJob(InputInterface $input, OutputInterface $output) { $job = $input->getArgument('job'); if (empty($job)) { $api = new Api(); $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select a job', $api->getAllJobs()); $question->setErrorMessage('Job %s is invalid.'); $job = $helper->ask($input, $output, $question); $output->writeln('Selected Job: ' . $job); list($stackName) = explode(' ', $job); $input->setArgument('job', $stackName); } return $job; }
/** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { if ($input->getArgument('file')) { return; } /** @var StorageInterface $storage */ $storage = $this->getContainer()->get('storage'); $localFiles = $storage->localListing(); $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Which backup', $localFiles); $question->setErrorMessage('Backup %s is invalid.'); $question->setAutocompleterValues([]); $input->setArgument('file', $helper->ask($input, $output, $question)); $output->writeln(''); }
protected function interact(InputInterface $input, OutputInterface $output) { $this->metadata = []; $dialog = $this->getDialogHelper(); $moduleHandler = $this->getModuleHandler(); $drupal = $this->getDrupalHelper(); $questionHelper = $this->getQuestionHelper(); // --module option $module = $input->getOption('module'); if (!$module) { // @see Drupal\Console\Command\ModuleTrait::moduleQuestion $module = $this->moduleQuestion($output, $dialog); } $input->setOption('module', $module); // --class-name option $form_id = $input->getOption('form-id'); if (!$form_id) { $forms = []; // Get form ids from webprofiler if ($moduleHandler->moduleExists('webprofiler')) { $output->writeln('[-] <info>' . $this->trans('commands.generate.form.alter.messages.loading-forms') . '</info>'); $forms = $this->getWebprofilerForms(); } if (!empty($forms)) { $form_id = $dialog->askAndValidate($output, $dialog->getQuestion($this->trans('commands.generate.form.alter.options.form-id'), current(array_keys($forms))), function ($form) { return $form; }, false, '', array_combine(array_keys($forms), array_keys($forms))); } } if ($moduleHandler->moduleExists('webprofiler') && isset($forms[$form_id])) { $this->metadata['class'] = $forms[$form_id]['class']['class']; $this->metadata['method'] = $forms[$form_id]['class']['method']; $this->metadata['file'] = str_replace($drupal->getRoot(), '', $forms[$form_id]['class']['file']); $formItems = array_keys($forms[$form_id]['form']); $question = new ChoiceQuestion($this->trans('commands.generate.form.alter.messages.hide-form-elements'), array_combine($formItems, $formItems), '0'); $question->setMultiselect(true); $question->setValidator(function ($answer) { return $answer; }); $formItemsToHide = $questionHelper->ask($input, $output, $question); $this->metadata['unset'] = array_filter(array_map('trim', explode(',', $formItemsToHide))); } $input->setOption('form-id', $form_id); $output->writeln($this->trans('commands.generate.form.alter.messages.inputs')); // @see Drupal\Console\Command\FormTrait::formQuestion $form = $this->formQuestion($output, $dialog); $input->setOption('inputs', $form); }