/** * {@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>'); } }
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) { $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); }
/** * {@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)); }
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); } }
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}</>"); }
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); }
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)); }
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(''); }
/** * @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)); }
/** * Predeterminado::execute() * * ejecuta el proceso correspondiente de la * consola * * @param object $input * @param object $output * @return raw */ protected function execute(InputInterface $input, OutputInterface $output) { $app = is_bool(ConfigAcceso::leer('Predeterminado', 'fuente', 'aplicacion')) == true ? 'NO ASIGNADA' : ConfigAcceso::leer('Predeterminado', 'fuente', 'aplicacion'); $output->writeln("\n\n\tSELECCION DE APLICACION PREDETERMINADA\n\n"); $output->writeln("APLICACION: " . $app); $listaPreguntas = $this->listadoAplicaciones($input, $output); if (count($listaPreguntas) >= 1) { $ayuda = $this->getHelper('question'); $pregunta = new ChoiceQuestion("\n<question>Seleccione la aplicación predeterminada:</question>\n", $listaPreguntas); $pregunta->setErrorMessage('La opción seleccionada no es valida'); $input->respuesta = $ayuda->ask($input, $output, $pregunta); $this->escrituraConfg($input, $output); } else { $output->writeln("\n\n<error>No hay aplicaciones para configurar como Predeterminado</error>\n\n"); } }
/** * Configures the interactive part of the console application * @param InputInterface $input The console input object * @param OutputInterface $output The console output object */ protected function interact(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $hash = !empty($input->getOption('hash')) ? json_decode(base64_decode($input->getOption('hash'))) : ''; if (empty($input->getArgument('project'))) { $this->connect($input->getOption('url'), $input->getOption('auth')); $question = new ChoiceQuestion('Project: ', Project::getInstance()->getAllProjectKeys(), !empty($hash->project) ? $hash->project : null); $question->setErrorMessage('Project %s is invalid'); $input->setArgument('project', $helper->ask($input, $output, $question)); } if (empty($input->getArgument('title'))) { $question = new Question('Title: ', !empty($hash->subject) ? $hash->subject : null); $input->setArgument('title', $helper->ask($input, $output, $question)); } if (empty($input->getArgument('description'))) { $question = new Question('Description: ', !empty($hash->message) ? $hash->message : null); $input->setArgument('description', $helper->ask($input, $output, $question)); } if (empty($input->getOption('priority'))) { $question = new ChoiceQuestion('Priority: ', $this->priorities, !empty($hash->priority) ? $hash->priority : 'Medium'); $question->setErrorMessage('Priority %s is invalid'); $input->setOption('priority', $helper->ask($input, $output, $question)); } if (!empty($this->config['custom'])) { $this->availableConfig = Issue::getInstance()->getProjectIssueAvailableConfig($input->getArgument('project')); foreach ($this->config['custom'] as $name => $argument) { if (empty($this->availableConfig->projects[0]->issuetypes[0]->fields->{$name}->name)) { continue; } switch ($argument['type']) { case 'ChoiceQuestion': $allowedValues = array(); $customField = $this->availableConfig->projects[0]->issuetypes[0]->fields->{$name}; foreach ($customField->allowedValues as $allowedValue) { $allowedValues[$allowedValue->id] = $allowedValue->value; } $question = new ChoiceQuestion($customField->name . ': ', $allowedValues, !empty($hash->{$name}) ? $hash->{$name} : null); $input->setArgument($name, $helper->ask($input, $output, $question)); break; case 'Question': default: $question = new Question($this->availableConfig->projects[0]->issuetypes[0]->fields->{$name}->name . ': ', !empty($hash->{$name}) ? $hash->{$name} : null); $input->setArgument($name, $helper->ask($input, $output, $question)); } } } }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $customProperty = array("hello" => "world", "answer" => 42); $title = "Push test"; $body = "push de test"; do { // Add a token $addTokenQuestion = new ChoiceQuestion('Which device do you want to target ?', array(1 => 'ios', 2 => 'android'), 1); $addTokenQuestion->setErrorMessage('Choice is invalid'); $response = $helper->ask($input, $output, $addTokenQuestion); $tokenQuestion = new Question('Enter the device token / registration id : '); $token = $helper->ask($input, $output, $tokenQuestion); $pushData = new PushData(); $device = null; switch ($response) { case 'ios': $pushData->setApnsCategory("debug"); $pushData->setApnsBadge(1); $customProperty = $this->getContainer()->get('serializer')->serialize($customProperty, 'json'); $pushData->setApnsCustomProperties($customProperty); $pushData->setApnsSound("default"); $pushData->setApnsText($body); $device = new IOSDevice(); $device->setRegistrationToken($token); break; case 'android': $payload = array('notification' => array('title' => $title, 'body' => $body, 'icon' => 'icon'), 'data' => $customProperty); $pushData->setGcmPayloadData($payload); $device = new AndroidDevice(); $device->setRegistrationToken($token); break; } // Send push $output->writeln(""); $sendQuestion = new ConfirmationQuestion("Sending a push message to {$token}, confirm push submission (y/n) ? ", true); if ($helper->ask($input, $output, $sendQuestion)) { $this->getContainer()->get('wassa_mps')->sendToMultipleDevices($pushData, array($device)); $output->writeln("-> Push sent to " . $token); } else { $output->writeln("-> Push was not sent"); } // Ask for another token $continueQuestion = new ConfirmationQuestion('Do you wish to send another push (y/n) ? ', true); } while ($helper->ask($input, $output, $continueQuestion)); }
protected function execute(InputInterface $input, OutputInterface $output) { // Style the output $output = $this->setOutputFormat($output); // Helper to ask questions through Console $helper = $this->getHelper('question'); $question = new ChoiceQuestion("\n<say>Please select which city you want to <high>delete</high></say>", $this->city->getAllBikestormingIDs()); $question->setErrorMessage('Please use the number in [brackets] to refer to the city.'); $bkid = $helper->ask($input, $output, $question); $question = new Question("\n<say>Password, please?: </say>"); $question->setHidden(true); $password = $helper->ask($input, $output, $question); if (md5($password) == 'f22ec0566c58b521e7f512d0bb55e67e') { return $this->city->deleteByBikestormingID($bkid); } $output->writeln("<error>Wrong password :/</error>"); }
public function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Do you agree with the terms and conditions for Craft (n)?', array('y' => 'yes', 'n' => 'no'), 'n'); $question->setErrorMessage('<error>You must agree to the terms and conditions.</error>'); $answer = $helper->ask($input, $output, $question); $directory = getcwd() . '/' . $input->getArgument('directory'); if ($answer == 'no') { $output->writeln('<error>You must agree with the terms and conditions to continue!</error>'); $output->writeln('<info>Craft License is located here: http://buildwithcraft.com/license</info>'); exit(1); } $this->doesDirectoryExist($directory, $output); $this->download($output, $zip = $this->createZip()); $this->unzip($zip, $directory); $this->cleanUp($zip); $output->writeln('<comment>Craft installed and ready to rock!!!</comment>'); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->dump = Dump::load($input->getOption('output-dir')); $map = []; foreach ($this->dump->projects as $project) { $phases = collection_column($project->phases, 'name'); $statuses = array_keys($this->redmine->api('issue_status')->listing()); $map[$project->id] = []; $output->writeln("For project #{$project->id} '{$project->name}':"); foreach ($phases as $phase) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion("Map the AgileZen phase '{$phase}' to Redmine status:", $statuses); $question->setErrorMessage('Invalid status.'); $map[$project->id][$phase] = $helper->ask($input, $output, $question); } } $this->dump->phaseMap = $map; $this->dump->write(); }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $output->writeln(PHP_EOL); $output->writeln(' ████████╗██╗ ██╗██╗ ██╗███╗ ███╗ ██████╗███╗ ██╗ ██████╗ '); $output->writeln(' ╚══██╔══╝██║ ██║██║ ██║████╗ ████║██╔════╝████╗ ██║██╔═══██╗'); $output->writeln(' ██║ ███████║██║ ██║██╔████╔██║██║ ██╔██╗ ██║██║ ██║'); $output->writeln(' ██║ ██╔══██║██║ ██║██║╚██╔╝██║██║ ██║╚██╗██║██║ ██║'); $output->writeln(' ██║ ██║ ██║╚██████╔╝██║ ╚═╝ ██║╚██████╗██║ ╚████║╚██████╔╝'); $output->writeln(' ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═══╝ ╚═════╝ '); $output->writeln(str_repeat(' ', 40 - strlen(VERSION)) . 'The thumbnail generator - ' . VERSION); $output->writeln(' By Tacnoman'); $output->writeln(''); // ENV $output->writeln('Configuring the environment variables:'); $question = new Question('Enter the thumcno_path (keep in blank if you want to use the root path): <info>[' . dirname(__DIR__) . ']</info>: ', false); $thumcnoPath = $helper->ask($input, $output, $question); $question = new ChoiceQuestion('Permit use for only domain? ', ['no', 'yes'], 0); $question->setErrorMessage('Answer `%s` is invalid.'); $useForOnlyDomain = $helper->ask($input, $output, $question); $envFileContent = ''; if ($thumcnoPath) { $thumcnoPath = rtrim($thumcnoPath, '/'); $envFileContent .= 'THUMCNO_PATH=' . $thumcnoPath . PHP_EOL; $_ENV['THUMCNO_PATH'] = $thumcnoPath; } else { $_ENV['THUMCNO_PATH'] = dirname(__DIR__); } $envFileContent .= 'PERMIT_ONLY_DOMAIN='; $envFileContent .= $useForOnlyDomain == 'yes' ? '1' : '0'; $arq = fopen(dirname(__DIR__) . '/.env', 'w'); fwrite($arq, $envFileContent); fclose($arq); $output->write(PHP_EOL); $output->writeln(' <info>✔</info> File .env was created'); // Cache dir $this->createCacheDir(); $output->writeln(' <info>✔</info> The cache dir was created' . PHP_EOL); $output->writeln('<info>The project was successfully configured. Now, you can run:</info>' . PHP_EOL); $output->writeln(' <comment>$ ./thumcno server</comment>' . PHP_EOL); $output->writeln('And use the THUMCNO.' . PHP_EOL); }
/** * @return int|null|void */ protected function serve() { $this->options = ['user' => $this->input->getOption('user'), 'state' => $this->input->getOption('state')]; $this->validateOptions(); $helper = $this->getHelper('question'); $data = []; $this->output->writeln('<green>Setting User State</green>'); $this->output->writeln(''); if (!$this->options['user']) { // Get username and validate $question = new Question('Enter a <yellow>username</yellow>: '); $question->setValidator(function ($value) { return $this->validate('user', $value); }); $username = $helper->ask($this->input, $this->output, $question); } else { $username = $this->options['user']; } if (!$this->options['state'] && !count(array_filter($this->options))) { // Choose State $question = new ChoiceQuestion('Please choose the <yellow>state</yellow> for the account:', array('enabled' => 'Enabled', 'disabled' => 'Disabled'), 'enabled'); $question->setErrorMessage('State %s is invalid.'); $data['state'] = $helper->ask($this->input, $this->output, $question); } else { $data['state'] = $this->options['state'] ?: 'enabled'; } // Lowercase the username for the filename $username = strtolower($username); // Grab the account file and read in the information before setting the file (prevent setting erase) $oldUserFile = CompiledYamlFile::instance(self::getGrav()['locator']->findResource('user://accounts/' . $username . YAML_EXT, true, true)); $oldData = $oldUserFile->content(); //Set the state feild to new state $oldData['state'] = $data['state']; // Create user object and save it using oldData (with updated state) $user = new User($oldData); $file = CompiledYamlFile::instance(self::getGrav()['locator']->findResource('user://accounts/' . $username . YAML_EXT, true, true)); $user->file($file); $user->save(); $this->output->writeln(''); $this->output->writeln('<green>Success!</green> User <cyan>' . $username . '</cyan> state set to .' . $data['state']); }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $key = $this->eveApiKeyManager->create($input->getArgument('username'), $input->getArgument('keyID'), $input->getArgument('vCode')); $this->phealManager->activateKey($key); // Store all the characters from the key $characters = $this->characterManager->discoverAndPersistCharacters(); // Create a simple array with only the names in it. $names = array(); foreach ($characters as $char) { $names[] = $char->getName(); } // Ask the question to get the chosen name $question = new ChoiceQuestion('Please select your a character', $names, 0); $question->setErrorMessage('Chosen character %s is invalid.'); $name = $helper->ask($input, $output, $question); $character = $this->characterManager->findCharacterByName($name); $key->setCharacter($character); $this->eveApiKeyManager->persist($key); $output->writeln('Your new key has been stored'); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); // Select Role $roles = $this->getContainer()->getParameter('security.role_hierarchy.roles'); $question = new ChoiceQuestion('Select role', array_keys($roles)); $question->setErrorMessage('Role %s is invalid.'); $role = $helper->ask($input, $output, $question); // Select Permission(s) $permissionMap = $this->getContainer()->get('security.acl.permission.map'); $question = new ChoiceQuestion('Select permissions(s) (seperate by ",")', $permissionMap->getPossiblePermissions()); $question->setMultiselect(true); $mask = array_reduce($helper->ask($input, $output, $question), function ($a, $b) use($permissionMap) { return $a | $permissionMap->getMasks($b, null)[0]; }, 0); /* @var EntityManager $em */ $em = $this->getContainer()->get('doctrine.orm.entity_manager'); /* @var MutableAclProviderInterface $aclProvider */ $aclProvider = $this->getContainer()->get('security.acl.provider'); /* @var ObjectIdentityRetrievalStrategyInterface $oidStrategy */ $oidStrategy = $this->getContainer()->get('security.acl.object_identity_retrieval_strategy'); // Fetch all nodes & grant access $nodes = $em->getRepository('KunstmaanNodeBundle:Node')->findAll(); foreach ($nodes as $node) { $objectIdentity = $oidStrategy->getObjectIdentity($node); /** @var Acl $acl */ $acl = $aclProvider->findAcl($objectIdentity); $securityIdentity = new RoleSecurityIdentity($role); /** @var Entry $ace */ foreach ($acl->getObjectAces() as $index => $ace) { if (!$ace->getSecurityIdentity()->equals($securityIdentity)) { continue; } $acl->updateObjectAce($index, $mask); break; } $aclProvider->updateAcl($acl); } $output->writeln(count($nodes) . ' nodes processed.'); }
/** * Ask questions * * @param Set $set A Certificationy questions Set instance * @param InputInterface $input A Symfony Console input instance * @param OutputInterface $output A Symfony Console output instance */ protected function askQuestions(Set $set, InputInterface $input, OutputInterface $output) { $questionHelper = $this->getHelper('question'); $showMultipleChoice = $input->getOption('show-multiple-choice'); $questionCount = 1; foreach ($set->getQuestions() as $i => $question) { $choiceQuestion = new ChoiceQuestion(sprintf('Question <comment>#%d</comment> [<info>%s</info>] %s' . ($showMultipleChoice === true ? "\n" . 'This question <comment>' . ($question->isMultipleChoice() === true ? 'IS' : 'IS NOT') . "</comment> multiple choice." : ""), $questionCount++, $question->getCategory(), $question->getQuestion()), $question->getAnswersLabels()); $multiSelect = $showMultipleChoice === true ? $question->isMultipleChoice() : true; $choiceQuestion->setMultiselect($multiSelect); $choiceQuestion->setErrorMessage('Answer %s is invalid.'); $answer = $questionHelper->ask($input, $output, $choiceQuestion); $answers = true === $multiSelect ? $answer : array($answer); $answer = true === $multiSelect ? implode(', ', $answer) : $answer; $set->setAnswer($i, $answers); if ($input->getOption("training")) { $uniqueSet = new Set(array($i => $question)); $uniqueSet->setAnswer($i, $answers); $this->displayResults($uniqueSet, $output); } $output->writeln('<comment>✎ Your answer</comment>: ' . $answer . "\n"); } }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $question = new Question('Please enter the domain to remove: <info>(without http://)</info>: ', ''); $domain = $helper->ask($input, $output, $question); $question = new ChoiceQuestion('Are you sure delete the domain <comment>' . $domain . '</comment>: ', ['yes', 'no'], 0); $question->setErrorMessage('Answer `%s` is invalid.'); $answer = $helper->ask($input, $output, $question); if ($answer == 'no') { return; } $path = $_ENV['THUMCNO_PATH'] . '/apps/' . $domain . '.ini'; if (!file_exists($path)) { $output->writeln('<fg=red>ERROR: The domain does not exist. Path: ' . $path . '</>' . PHP_EOL); return; } unlink($path); $output->writeln(PHP_EOL); $output->writeln('================'); $output->writeln('You removed the file: <fg=red>' . $path . '</>.'); $output->writeln(PHP_EOL); }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); if ($app_name = $input->getArgument('app')) { } else { $question = new ChoiceQuestion('Which app would you like to update?', array_keys($this->director->config['apps']), 0); $question->setErrorMessage('Color %s is invalid.'); $app_name = $helper->ask($input, $output, $question); $output->writeln('You have just selected: ' . $app_name); } $app =& $this->director->config['apps'][$app_name]; // App Name $question = new Question("System name of your project? ({$app['name']})", $app['name']); $app['name'] = $helper->ask($input, $output, $question); // App Description $question = new Question("Description? ({$app['description']})", $app['description']); $app['description'] = $helper->ask($input, $output, $question); // App Source $question = new Question("Source code repository URL? ({$app['source_url']})", $app['source_url']); $app['source_url'] = $helper->ask($input, $output, $question); $this->director->saveData(); }
protected function interact(InputInterface $input, OutputInterface $output) { $logGroupName = $input->getArgument('group') ?: '*'; $repository = new Repository(); $groups = $repository->findLogGroups($logGroupName); if (count($groups) == 0) { throw new \InvalidArgumentException('Could not find any matching log groups'); } elseif (count($groups) == 1) { $logGroupName = $groups->getFirst()->getLogGroupName(); } else { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select a log group', $groups->flatten('getLogGroupName')); $question->setErrorMessage('Log group %s is invalid.'); $logGroupName = $helper->ask($input, $output, $question); $output->writeln('Selected log group: ' . $logGroupName); } $input->setArgument('group', $logGroupName); $logStreamName = $input->getArgument('stream') ?: '*'; if ($logStreamName == '__FIRST__') { $streams = $repository->findLogStreams($logGroupName); $logStreamName = $streams->getFirst()->getLogStreamName(); } else { $streams = $repository->findLogStreams($logGroupName, $logStreamName); if (count($streams) == 0) { throw new \InvalidArgumentException('Could not find any matching log streams'); } elseif (count($streams) == 1) { $logStreamName = $streams->getFirst()->getLogStreamName(); } else { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select a log stream', $streams->flatten('getLogStreamName')); $question->setErrorMessage('Log stream %s is invalid.'); $logStreamName = $helper->ask($input, $output, $question); $output->writeln('Selected log stream: ' . $logStreamName); } } $input->setArgument('stream', $logStreamName); }
private function findProperServiceName(InputInterface $input, OutputInterface $output, ContainerBuilder $builder, $name) { if ($builder->has($name) || !$input->isInteractive()) { return $name; } $matchingServices = $this->findServiceIdsContaining($builder, $name); if (empty($matchingServices)) { throw new \InvalidArgumentException(sprintf('No services found that match "%s".', $name)); } $question = new ChoiceQuestion('Choose a number for more information on the service', $matchingServices); $question->setErrorMessage('Service %s is invalid.'); return $this->getHelper('question')->ask($input, $output, $question); }