php Symfony-Component-Console-Question-ChoiceQuestion类(方法)实例源码

下面列出了php Symfony-Component-Console-Question-ChoiceQuestion 类(方法)源码代码实例,从而了解它的用法。

作者:stopfsted    项目:ilio   
/**
  * {@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>');
     }
 }

作者:hypejunctio    项目:elgg-cl   
/**
  * {@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();
 }

作者:jingdo    项目:pickl   
/**
  * @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');
         }
     }
 }

作者:eduardoled    项目:schoolmanage   
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);
 }

作者:nanband    项目:cor   
/**
  * {@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));
 }

作者:clarolin    项目:distributio   
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);
 }

作者:Restless-E    项目:GeneratorBundl   
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);
 }

作者:desteban    项目:taskreporter-   
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);
 }

作者:Josek    项目:FileTemplat   
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, '/\\');
 }

作者:symfon    项目:symfon   
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);
    }

作者:aoepeopl    项目:stackformatio   
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);
     }
 }

作者:pjcdawkin    项目:console-for   
/**
  * {@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;
 }

作者:jeff-pucket    项目:mysql-dt   
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}</>");
 }

作者:jousc    项目:clitool   
/**
  * 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;
 }

作者:mnic    项目:DrupalConsol   
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);
 }

作者:vinodpanicke    项目:drupalci_testbo   
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;
 }

作者:vinodpanicke    项目:drupalci_testbo   
/**
  * {@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>");
         }
     }
 }

作者:afflict    项目:webde   
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);
 }

作者:junior057    项目:cru   
/**
  * @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);
     }
 }

作者:chi-tec    项目:drupal-code-generato   
/**
  * 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);
     }
 }


问题


面经


文章

微信
公众号

扫码关注公众号