当前位置: 首页>>代码示例>>PHP>>正文


PHP Question::setValidator方法代码示例

本文整理汇总了PHP中Symfony\Component\Console\Question\Question::setValidator方法的典型用法代码示例。如果您正苦于以下问题:PHP Question::setValidator方法的具体用法?PHP Question::setValidator怎么用?PHP Question::setValidator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Symfony\Component\Console\Question\Question的用法示例。


在下文中一共展示了Question::setValidator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: informAboutStructure

 /**
  * 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);
 }
开发者ID:broeser,项目名称:feeld,代码行数:41,代码来源:SymfonyConsoleDisplay.php

示例2: askQuestion

 /**
  * @param string|Question $question Question text or a Question object
  * @param null|string $default The default answer
  * @param bool|\Closure $requireAnswer True for not-empty validation, or a closure for custom validation
  * @return string User's answer
  */
 protected function askQuestion($question, $default = null, $requireAnswer = true)
 {
     if (!$this->questionHelper) {
         $this->questionHelper = $this->getHelper("question");
     }
     if (!$question instanceof Question) {
         if (strpos($question, '<question>') === false) {
             $question = '<question>' . $question . '</question> ';
         }
         if ($default !== null) {
             $question .= "({$default}) ";
         }
         $question = new Question($question, $default);
     }
     if (is_callable($requireAnswer)) {
         $question->setValidator($requireAnswer);
     } elseif ($requireAnswer) {
         $question->setValidator(function ($answer) {
             if (trim($answer) == '') {
                 throw new \Exception('You must provide an answer to this question');
             }
             return $answer;
         });
     }
     return $this->questionHelper->ask($this->input, $this->output, $question);
 }
开发者ID:rhubarbphp,项目名称:custard,代码行数:32,代码来源:CustardCommand.php

示例3: buildQuestion

 /**
  * @return SimpleQuestion
  */
 private function buildQuestion()
 {
     $question = new SimpleQuestion('<question>Enter your project homepage:</question>');
     $question->setValidator($this->buildValidator());
     $question->setMaxAttempts(3);
     return $question;
 }
开发者ID:raphhh,项目名称:samurai,代码行数:10,代码来源:HomepageQuestion.php

示例4: execute

 /**
  * Executes the command.
  * @param InputInterface  $input
  * @param OutputInterface $output
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!$this->getGitHelper()->available()) {
         throw new \Exception('Is not a git project.');
     }
     $git = $this->getGitHelper();
     do {
         $tags = $git->getTags();
         foreach ($tags as $id => $tagName) {
             $output->writeln(sprintf('[%s] %s', $id, $tagName));
         }
         /* @var $question \Symfony\Component\Console\Helper\QuestionHelper */
         $question = $this->getHelper('question');
         $tagQuestion = new Question('Which branch should deleted? ');
         $tagQuestion->setValidator(function ($answer) use($tags) {
             if (!isset($tags[$answer])) {
                 throw new \Exception($answer . ' is not a valid value');
             }
         });
         $tagQuestion->setMaxAttempts(3);
         $answer = $question->ask($input, $output, $tagQuestion);
         $git->deleteTag($tags[$answer]);
         $deleteOtherTagQuestion = new Question('Delete another tag/branch? [y/n]: ');
         $deleteOtherTag = $question->ask($input, $output, $deleteOtherTagQuestion);
     } while (strtolower(substr($deleteOtherTag, 0, 1)) == 'y');
 }
开发者ID:sseidelmann,项目名称:devutils,代码行数:32,代码来源:RemoveTagCommand.php

示例5: execute

 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);
 }
开发者ID:plehatron,项目名称:receipt-validation,代码行数:27,代码来源:VerifyCommand.php

示例6: buildAuthorQuestion

 /**
  * @return SimpleQuestion
  */
 private function buildAuthorQuestion()
 {
     $question = new SimpleQuestion('<question>Enter the author (name <mail@mail.com>):</question>');
     $question->setValidator($this->buildValidator());
     $question->setMaxAttempts(3);
     return $question;
 }
开发者ID:raphhh,项目名称:samurai,代码行数:10,代码来源:AuthorQuestion.php

示例7: interact

 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);
         }
     }
 }
开发者ID:hanabi1,项目名称:vagrant-manager,代码行数:26,代码来源:VagrantCommand.php

示例8: useSymfonyQuestion

 /**
  * @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);
 }
开发者ID:devonzara,项目名称:laravel,代码行数:12,代码来源:AutoComplete.php

示例9: interact

 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws \Exception
  * @throws \Symfony\Component\Console\Exception\ExceptionInterface
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     # print the status list
     /** @var StatusCommand $command */
     $command = $this->getApplication()->find('status');
     $statusInput = new ArrayInput(array(), $command->getDefinition());
     $command->run($statusInput, $output);
     foreach (array_keys($this->actions) as $name) {
         # ask with boxes to handle
         $helper = $this->getHelper('question');
         $question = new Question('<fg=yellow>' . "Select box/boxes to " . $name . ' []:</> ', 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 ($answer != "" && !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)) {
             $this->actions[$name]["boxes"] = $answer;
         }
     }
 }
开发者ID:AndreKlang,项目名称:vagrant-manager,代码行数:33,代码来源:MultiCommand.php

示例10: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $em = $this->getContainer()->get('doctrine')->getManager();
     $helper = $this->getHelper('question');
     $output->writeln("\n<question>                                      ");
     $output->writeln(' Welcome to the Fbeen slug generator. ');
     $output->writeln("                                      </question>\n");
     $entityName = $input->getArgument('entity');
     if (!$entityName) {
         $output->writeln('This command helps you to update slugs on an entire table.');
         $output->writeln('First, you need to give the entity for which you want to generate the slugs.');
         $output->writeln("\nYou must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.\n");
         $question = new Question('<info>The Entity shortcut name: </info>');
         $question->setValidator(array('Sensio\\Bundle\\GeneratorBundle\\Command\\Validators', 'validateEntityName'));
         $autocompleter = new EntitiesAutoCompleter($em);
         $autocompleteEntities = $autocompleter->getSuggestions();
         $question->setAutocompleterValues($autocompleteEntities);
         $entityName = $helper->ask($input, $output, $question);
     }
     $entities = $em->getRepository($entityName)->findAll();
     $question = new ConfirmationQuestion('<info>Continue generating slugs for ' . $entityName . '</info> [<comment>no</comment>]? ', false);
     if (!$helper->ask($input, $output, $question)) {
         return;
     }
     $output->writeln("\nGenerating the slugs...");
     $slugupdater = new SlugUpdater();
     foreach ($entities as $entity) {
         $slugupdater->preUpdate(new LifecycleEventArgs($entity, $em));
         $em->flush();
     }
     $output->writeln("\nDone!\n");
 }
开发者ID:fbeen,项目名称:uniqueslugbundle,代码行数:32,代码来源:SlugCommand.php

示例11: interact

 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);
 }
开发者ID:Restless-ET,项目名称:GeneratorBundle,代码行数:34,代码来源:GenerateAdminCommand.php

示例12: confirmSend

 private function confirmSend($input, $output)
 {
     //Symfony の Console コンポーネ ントには、確認プロンプトを出したり、
     //そこでの入力値をバリデーションしたりするための機能が
     // Questionとして組み込まれています。
     $qHelper = $this->getHelper('question');
     //Question クラス
     $question = new Question('通知メールを送信しますか? [y/n]: ', null);
     //setValidator( )メソッドに、バリデーション時に呼び出すコールバックを渡します
     //引数:入力された値
     //戻り値:正常な場合はバリデーション後の値、エラーがある場合は例外をスロー
     $question->setValidator(function ($answer) {
         //strtolower 大文字を小文字に substrは$answerの0番目の1文字を返す
         $answer = strtolower(substr($answer, 0, 1));
         if (!in_array($answer, ['y', 'n'])) {
             throw new \RuntimeException('yまたはnを入力してください');
         }
         return $answer;
     });
     //❺許容する試行回数の設定
     $question->setMaxAttempts(3);
     //プロンプトを表示して回答を得る
     //Questionヘルパのask( )メソッドを呼び出します。ask( )メソッドの戻り値は、
     //入力バリデーション後の値です。これが'y'だった場合は、confirmSend( )メソッドの戻り値として
     // true が返るようにしています。
     return $qHelper->ask($input, $output, $question) == 'y';
 }
开发者ID:dsaa151562000,项目名称:symphony2,代码行数:27,代码来源:NotifyUnprocessedInquiryCommand.php

示例13: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var QuestionHelper $questionHelper */
     $questionHelper = $this->getHelper('question');
     $usernameQuestion = new Question('E-mail: ');
     $usernameQuestion->setValidator(function ($value) {
         if (trim($value) === '') {
             throw new \Exception('E-mail can not be empty');
         }
         if (!Validators::isEmail($value)) {
             throw new \Exception('E-mail is not valid');
         }
         return $value;
     });
     $passwordQuestion = new Question('Password: ');
     $passwordQuestion->setValidator(function ($value) {
         if (trim($value) === '') {
             throw new \Exception('The password can not be empty');
         }
         return $value;
     });
     $passwordQuestion->setHidden(TRUE);
     $passwordQuestion->setHiddenFallback(FALSE);
     $username = $questionHelper->ask($input, $output, $usernameQuestion);
     $password = $questionHelper->ask($input, $output, $passwordQuestion);
     $name = $questionHelper->ask($input, $output, new Question('Name: '));
     $user = $this->userFacade->add($username, $password, $name);
     $output->writeln('User ' . $user->getEmail() . ' was successfully created!');
 }
开发者ID:wodcz,项目名称:sandbox,代码行数:29,代码来源:CreateUser.php

示例14: interact

 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getQuestionHelper();
     $questionHelper->writeSection($output, 'Welcome to the Parse.com CRUD generator');
     // namespace
     $output->writeln(array('', 'This command helps you generate CRUD controllers and templates.', 'You must use the shortcut notation like <comment>AcmeBlogBundle:Post</comment>.', ''));
     if ($input->hasArgument('parse-entity-name') && $input->getArgument('parse-entity-name') != '') {
         $input->setOption('parse-entity-name', $input->getArgument('parse-entity-name'));
     }
     $question = new Question($questionHelper->getQuestion('The Entity shortcut name', $input->getOption('parse-entity-name')), $input->getOption('parse-entity-name'));
     $question->setValidator(array('BcTic\\ParseCrudGenerator\\CrudGeneratorBundle\\Command\\Validators', 'validateParseEntityName'));
     $autocompleter = new EntitiesAutoCompleter($this->getContainer()->get('doctrine')->getManager());
     $autocompleteEntities = $autocompleter->getSuggestions();
     $question->setAutocompleterValues($autocompleteEntities);
     $entity = $questionHelper->ask($input, $output, $question);
     $input->setOption('parse-entity-name', $entity);
     list($bundle, $entity) = $this->parseShortcutNotation($entity);
     // 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), ''));
 }
开发者ID:mliell,项目名称:symfony-parse-crud-generator,代码行数:25,代码来源:GenerateParseCrudCommand.php

示例15: interact

 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getQuestionHelper();
     $questionHelper->writeSection($output, 'Welcome to the Kunstmaan Article generator');
     $inputAssistant = GeneratorUtils::getInputAssistant($input, $output, $questionHelper, $this->getApplication()->getKernel(), $this->getContainer());
     $inputAssistant->askForNamespace(array('', 'This command helps you to generate the Article classes.', 'You must specify the namespace of the bundle where you want to generate the classes in.', 'Use <comment>/</comment> instead of <comment>\\ </comment>for the namespace delimiter to avoid any problem.', ''));
     // entity
     $entity = $input->getOption('entity') ? $input->getOption('entity') : null;
     if (is_null($entity)) {
         $output->writeln(array('', 'You must specify a name for the collection of Article entities.', 'This name will be prefixed before every new entity.', 'For example entering <comment>News</comment> will result in:', '<comment>News</comment>OverviewPage, <comment>News</comment>Page and <comment>News</comment>Author', ''));
         $entityValidation = function ($entity) {
             if (empty($entity)) {
                 throw new \RuntimeException('You have to provide a entity name!');
             } elseif (!preg_match('/^[a-zA-Z][a-zA-Z_0-9]+$/', $entity)) {
                 throw new \InvalidArgumentException(sprintf("%s" . ' contains invalid characters', $entity));
             } else {
                 return $entity;
             }
         };
         $question = new Question($questionHelper->getQuestion('Name', $entity), $entity);
         $question->setValidator($entityValidation);
         $entity = $questionHelper->ask($input, $output, $question);
         $input->setOption('entity', $entity);
     }
     $inputAssistant->askForPrefix();
 }
开发者ID:axelvnk,项目名称:KunstmaanBundlesCMS,代码行数:26,代码来源:GenerateArticleCommand.php


注:本文中的Symfony\Component\Console\Question\Question::setValidator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。