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); }
/** * {@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)); }
/** * {@inheritdoc} */ protected function handle() { $plugins = elgg_get_plugins('inactive'); if (empty($plugins)) { system_message('All plugins are active'); return; } $ids = array_map(function (ElggPlugin $plugin) { return $plugin->getID(); }, $plugins); $ids = array_values($ids); if ($this->option('all')) { $activate_ids = $ids; } else { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select plugins you would like to activate (comma-separated list of indexes)', $ids); $question->setMultiselect(true); $activate_ids = $helper->ask($this->input, $this->output, $question); } if (empty($activate_ids)) { throw new \RuntimeException('You must select at least one plugin'); } $plugins = []; foreach ($activate_ids as $plugin_id) { $plugins[] = elgg_get_plugin_from_id($plugin_id); } do { $additional_plugins_activated = false; foreach ($plugins as $key => $plugin) { if ($plugin->isActive()) { unset($plugins[$key]); continue; } if (!$plugin->activate()) { // plugin could not be activated in this loop, maybe in the next loop continue; } $ids = array('cannot_start' . $plugin->getID(), 'invalid_and_deactivated_' . $plugin->getID()); foreach ($ids as $id) { elgg_delete_admin_notice($id); } // mark that something has changed in this loop $additional_plugins_activated = true; unset($plugins[$key]); system_message("Plugin {$plugin->getFriendlyName()} has been activated"); } if (!$additional_plugins_activated) { // no updates in this pass, break the loop break; } } while (count($plugins) > 0); if (count($plugins) > 0) { foreach ($plugins as $plugin) { $msg = $plugin->getError(); $string = $msg ? 'admin:plugins:activate:no_with_msg' : 'admin:plugins:activate:no'; register_error(elgg_echo($string, array($plugin->getFriendlyName()))); } } elgg_flush_caches(); }
/** * @param string $path * @param InputInterface $input * @param OutputInterface $output */ protected function binaryInstallWindows($path, InputInterface $input, OutputInterface $output) { $php = Engine::factory(); $table = new Table($output); $table->setRows([['<info>' . $php->getName() . ' Path</info>', $php->getPath()], ['<info>' . $php->getName() . ' Version</info>', $php->getVersion()], ['<info>Compiler</info>', $php->getCompiler()], ['<info>Architecture</info>', $php->getArchitecture()], ['<info>Thread safety</info>', $php->getZts() ? 'yes' : 'no'], ['<info>Extension dir</info>', $php->getExtensionDir()], ['<info>php.ini</info>', $php->getIniPath()]])->render(); $inst = Install::factory($path); $progress = $this->getHelperSet()->get('progress'); $inst->setProgress($progress); $inst->setInput($input); $inst->setOutput($output); $inst->install(); $deps_handler = new Windows\DependencyLib($php); $deps_handler->setProgress($progress); $deps_handler->setInput($input); $deps_handler->setOutput($output); $helper = $this->getHelperSet()->get('question'); $cb = function ($choices) use($helper, $input, $output) { $question = new ChoiceQuestion('Multiple choices found, please select the appropriate dependency package', $choices); $question->setMultiselect(false); return $helper->ask($input, $output, $question); }; foreach ($inst->getExtDllPaths() as $dll) { if (!$deps_handler->resolveForBin($dll, $cb)) { throw new \Exception('Failed to resolve dependencies'); } } }
protected function interact(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); if (trim($input->getOption('name')) == '') { $question = new Question\Question('Please enter the client name: '); $question->setValidator(function ($value) { if (trim($value) == '') { throw new \Exception('The client name can not be empty'); } $doctrine = $this->getContainer()->get('doctrine'); $client = $doctrine->getRepository('AppBundle:Client')->findOneBy(['name' => $value]); if ($client instanceof \AppBundle\Entity\Client) { throw new \Exception('The client name must be unique'); } return $value; }); $question->setMaxAttempts(5); $input->setOption('name', $helper->ask($input, $output, $question)); } $grants = $input->getOption('grant-type'); if (!(is_array($grants) && count($grants))) { $question = new Question\ChoiceQuestion('Please select the grant types (defaults to password and facebook_access_token): ', [\OAuth2\OAuth2::GRANT_TYPE_AUTH_CODE, \OAuth2\OAuth2::GRANT_TYPE_CLIENT_CREDENTIALS, \OAuth2\OAuth2::GRANT_TYPE_EXTENSIONS, \OAuth2\OAuth2::GRANT_TYPE_IMPLICIT, \OAuth2\OAuth2::GRANT_TYPE_REFRESH_TOKEN, \OAuth2\OAuth2::GRANT_TYPE_USER_CREDENTIALS, 'http://grants.api.schoolmanager.ledo.eu.org/facebook_access_token'], '5,6'); $question->setMultiselect(true); $question->setMaxAttempts(5); $input->setOption('grant-type', $helper->ask($input, $output, $question)); } parent::interact($input, $output); }
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); }
public function choice($question, array $choices, $default = null, $multiple = false) { if (null !== $default) { $values = array_flip($choices); $default = $values[$default]; } $choiceQuestion = new ChoiceQuestion($question, $choices, $default); $choiceQuestion->setMultiselect($multiple); return $this->askQuestion($choiceQuestion); }
protected function getWebContainerNames($containers, InputInterface $input, OutputInterface $output) { # Prompt the user $helper = $this->getHelperSet()->get('question'); $containers[] = 'all'; $question = new ChoiceQuestion('<fg=cyan;bg=blue>Please select the numbers corresponding to which DrupalCI web environments to support. Separate multiple entries with commas. (Default: [0])</fg=cyan;bg=blue>', $containers, '0'); $question->setMultiselect(true); $results = $helper->ask($input, $output, $question); return $results; }
/** * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { // TODO: Ensure that configurations have been initialized // Get available config sets $helper = new ConfigHelper(); $configsets = $helper->getAllConfigSets(); $homedir = getenv('HOME'); // Check if passed argument is 'all' $names = $input->getArgument('setting'); if (empty($names)) { // If no argument passed, prompt the user for which config set to display $qhelper = $this->getHelper('question'); $message = "<question>Choose the number corresponding to which configuration set(s) to display:</question> "; $output->writeln($message); $message = "<comment>Separate multiple values with commas.</comment>"; $options = array_merge(array_keys($configsets), array('current', 'all')); $question = new ChoiceQuestion($message, $options, 0); $question->setMultiselect(TRUE); $names = $qhelper->ask($input, $output, $question); } if (in_array('all', $names)) { $names = array_keys($configsets); } // Is passed config set valid? foreach ($names as $key => $name) { if ($name == 'current') { $env_vars = $helper->getCurrentEnvVars(); $output->writeln("<info>---------------- Start config set: <options=bold>CURRENT DCI ENVIRONMENT</options=bold></info> ----------------</info>"); $output->writeln("<comment;options=bold>Defined in ~/.drupalci/config:</comment;options=bold>"); $contents = $helper->getCurrentConfigSetContents(); foreach ($contents as $line) { $parsed = explode("=", $line); if (!empty($parsed[0]) && !empty($parsed[1])) { $output->writeln("<comment>" . strtoupper($parsed[0]) . ": </comment><info>" . $parsed[1] . "</info>"); } } if (!empty($env_vars)) { $output->writeln("<comment;options=bold>Defined in Environment Variables:</comment;options=bold>"); foreach ($env_vars as $key => $value) { $output->writeln("<comment>" . strtoupper($key) . ": </comment><info>" . $value . "</info>"); } $output->writeln("<info>------------ End config set: <options=bold>CURRENT DCI ENVIRONMENT</options=bold></info> ----------------</info>"); $output->writeln(''); } } elseif (in_array($name, array_keys($configsets))) { $contents = file_get_contents($configsets[$name]); $output->writeln("<info>---------------- Start config set: <options=bold>{$name}</options=bold></info> ----------------</info>"); $output->writeln($contents); $output->writeln("<info>------------ End config set: <options=bold>{$name}</options=bold></info> ----------------</info>"); $output->writeln(''); } else { $output->writeln("<error>Configuration set '{$name}' not found. Skipping.</error>"); } } }
/** * @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); } }
public function askRoles($all, $input, $output, $container, $helper) { $roles = $container->get('claroline.persistence.object_manager')->getRepository('ClarolineCoreBundle:Role')->findAllPlatformRoles(); $roleNames = array_map(function ($role) { return $role->getName(); }, $roles); $roleNames[] = 'NONE'; $questionString = $all ? 'Roles to exclude: ' : 'Roles to include: '; $question = new ChoiceQuestion($questionString, $roleNames); $question->setMultiselect(true); $roleNames = $helper->ask($input, $output, $question); return array_filter($roles, function ($role) use($roleNames) { return in_array($role->getName(), $roleNames); }); }
protected function interact(InputInterface $input, OutputInterface $output) { $this->metadata = []; $dialog = $this->getDialogHelper(); $moduleHandler = $this->getModuleHandler(); $drupal = $this->getDrupalHelper(); $questionHelper = $this->getQuestionHelper(); // --module option $module = $input->getOption('module'); if (!$module) { // @see Drupal\Console\Command\ModuleTrait::moduleQuestion $module = $this->moduleQuestion($output, $dialog); } $input->setOption('module', $module); // --class-name option $form_id = $input->getOption('form-id'); if (!$form_id) { $forms = []; // Get form ids from webprofiler if ($moduleHandler->moduleExists('webprofiler')) { $output->writeln('[-] <info>' . $this->trans('commands.generate.form.alter.messages.loading-forms') . '</info>'); $forms = $this->getWebprofilerForms(); } if (!empty($forms)) { $form_id = $dialog->askAndValidate($output, $dialog->getQuestion($this->trans('commands.generate.form.alter.options.form-id'), current(array_keys($forms))), function ($form) { return $form; }, false, '', array_combine(array_keys($forms), array_keys($forms))); } } if ($moduleHandler->moduleExists('webprofiler') && isset($forms[$form_id])) { $this->metadata['class'] = $forms[$form_id]['class']['class']; $this->metadata['method'] = $forms[$form_id]['class']['method']; $this->metadata['file'] = str_replace($drupal->getRoot(), '', $forms[$form_id]['class']['file']); $formItems = array_keys($forms[$form_id]['form']); $question = new ChoiceQuestion($this->trans('commands.generate.form.alter.messages.hide-form-elements'), array_combine($formItems, $formItems), '0'); $question->setMultiselect(true); $question->setValidator(function ($answer) { return $answer; }); $formItemsToHide = $questionHelper->ask($input, $output, $question); $this->metadata['unset'] = array_filter(array_map('trim', explode(',', $formItemsToHide))); } $input->setOption('form-id', $form_id); $output->writeln($this->trans('commands.generate.form.alter.messages.inputs')); // @see Drupal\Console\Command\FormTrait::formQuestion $form = $this->formQuestion($output, $dialog); $input->setOption('inputs', $form); }
protected function interact(InputInterface $input, OutputInterface $output) { $params = ['old_string' => 'The string to match', 'new_string' => 'The string to replace']; foreach ($params as $argument => $argumentName) { if (!$input->getArgument($argument)) { $input->setArgument($argument, $this->askArgument($output, $argumentName)); } } $helper = $this->getHelper('question'); $entities = array_keys($this->getParsableEntities()); $question = new ChoiceQuestion('Entity to parse: ', $entities); $question->setMultiselect(true); while (null === ($entity = $input->getArgument('classes'))) { $entity = $helper->ask($input, $output, $question); $input->setArgument('classes', $entity); } }
protected function execute(InputInterface $input, OutputInterface $output) { $removeUsers = $input->getOption('user'); $removeGroups = $input->getOption('group'); $container = $this->getContainer(); $helper = $this->getHelper('question'); $workspaceManager = $this->getContainer()->get('claroline.manager.workspace_manager'); $roleManager = $this->getContainer()->get('claroline.manager.role_manager'); $question = new Question('Filter on code (continue if no filter)', null); $code = $helper->ask($input, $output, $question); $question = new Question('Filter on name (continue if no filter)', null); $name = $helper->ask($input, $output, $question); $workspaces = $workspaceManager->getNonPersonalByCodeAndName($code, $name); $om = $container->get('claroline.persistence.object_manager'); foreach ($workspaces as $workspace) { $roles = $roleManager->getRolesByWorkspace($workspace); $roleNames = array_map(function ($role) { return $role->getTranslationKey(); }, $roles); $roleNames[] = 'NONE'; $questionString = "Pick a role list for [{$workspace->getName()} - {$workspace->getCode()}]:"; $question = new ChoiceQuestion($questionString, $roleNames); $question->setMultiselect(true); $roleNames = $helper->ask($input, $output, $question); $pickedRoles = array_filter($roles, function ($role) use($roleNames) { return in_array($role->getTranslationKey(), $roleNames); }); $om->startFlushSuite(); foreach ($pickedRoles as $role) { if ($removeUsers) { $count = $om->getRepository('ClarolineCoreBundle:User')->countUsersByRole($role); $output->writeln("Removing {$count} users from role {$role->getTranslationKey()}"); $roleManager->emptyRole($role, RoleManager::EMPTY_USERS); } if ($removeGroups) { $count = $om->getRepository('ClarolineCoreBundle:Group')->countGroupsByRole($role); $output->writeln("Removing {$count} groups from role {$role->getTranslationKey()}"); $roleManager->emptyRole($role, RoleManager::EMPTY_GROUPS); } } $om->endFlushSuite(); } }
protected function execute(InputInterface $input, OutputInterface $output) { $dialog = $this->getDialogHelper(); $questionHelper = $this->getQuestionHelper(); $resource_id = $input->getArgument('resource-id'); $rest_resources = $this->getRestResources(); $rest_resources_ids = array_merge(array_keys($rest_resources['enabled']), array_keys($rest_resources['disabled'])); if (!$resource_id) { $resource_id = $dialog->askAndValidate($output, $dialog->getQuestion($this->trans('commands.rest.enable.arguments.resource-id'), ''), function ($resource_id) use($rest_resources_ids) { return $this->validateRestResource($resource_id, $rest_resources_ids, $this->getTranslator()); }, false, '', $rest_resources_ids); } $this->validateRestResource($resource_id, $rest_resources_ids, $this->getTranslator()); $input->setArgument('resource-id', $resource_id); // Calculate states available by resource and generate the question $resourcePluginManager = $this->getPluginManagerRest(); $plugin = $resourcePluginManager->getInstance(array('id' => $resource_id)); $states = $plugin->availableMethods(); $question = new ChoiceQuestion($this->trans('commands.rest.enable.arguments.states'), array_combine($states, $states), '0'); $state = $questionHelper->ask($input, $output, $question); $output->writeln($this->trans('commands.rest.enable.messages.selected-state') . ' ' . $state); // Get serializer formats available and generate the question. $formats = $this->getSerializerFormats(); $question = new ChoiceQuestion($this->trans('commands.rest.enable.messages.formats'), array_combine($formats, $formats), '0'); $question->setMultiselect(true); $formats = $questionHelper->ask($input, $output, $question); $output->writeln($this->trans('commands.rest.enable.messages.selected-formats') . ' ' . implode(', ', $formats)); // Get Authentication Provider and generate the question $authentication_providers = $this->getAuthenticationProviders(); $question = new ChoiceQuestion($this->trans('commands.rest.enable.messages.authentication-providers'), array_combine(array_keys($authentication_providers), array_keys($authentication_providers)), '0'); $question->setMultiselect(true); $authentication_providers = $questionHelper->ask($input, $output, $question); $output->writeln($this->trans('commands.rest.enable.messages.selected-authentication-providers') . ' ' . implode(', ', $authentication_providers)); $rest_settings = $this->getRestDrupalConfig(); $rest_settings[$resource_id][$state]['supported_formats'] = $formats; $rest_settings[$resource_id][$state]['supported_auth'] = $authentication_providers; $config = $this->getConfigFactory()->getEditable('rest.settings'); $config->set('resources', $rest_settings); $config->save(); // Run cache rebuild to enable rest routing $this->getChain()->addCommand('cache:rebuild', ['cache' => 'all']); }
/** * Get a list of roles from the user * * @param string[] $default * @param InputInterface $input * @param OutputInterface $output * @return string[] */ protected function getRoles(array $default = null, InputInterface $input, OutputInterface $output) { $roles_available = $this->getContainer()->get('orm.user_provider')->getAvailableRoles(); $helper = $this->getHelper('question'); $default_indices = []; $roles = []; foreach ($roles_available as $index => $role) { $roles[$index + 1] = $role; if (!$default) { $default = [$role]; } if (in_array($role, $default)) { $default_indices[] = $index + 1; } } $default_roles = implode(',', $default_indices); $roles_question = new ChoiceQuestion('User roles [' . $default_roles . ']: ', $roles, $default_roles); $roles_question->setMultiselect(true); return $helper->ask($input, $output, $roles_question); }
/** * {@inheritdoc} */ protected function handle() { $plugins = elgg_get_plugins('active'); if (empty($plugins)) { system_message('All plugins are inactive'); return; } $ids = array_map(function (ElggPlugin $plugin) { return $plugin->getID(); }, $plugins); $ids = array_values($ids); if ($this->option('all')) { $deactivate_ids = $ids; } else { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select plugins you would like to deactivate (comma-separated list of indexes)', $ids); $question->setMultiselect(true); $deactivate_ids = $helper->ask($this->input, $this->output, $question); } if (empty($deactivate_ids)) { throw new RuntimeException('You must select at least one plugin'); } $plugins = []; foreach ($deactivate_ids as $plugin_id) { $plugins[] = elgg_get_plugin_from_id($plugin_id); } foreach ($plugins as $plugin) { if (!$plugin->isActive()) { continue; } if (!$plugin->deactivate()) { $msg = $plugin->getError(); $string = $msg ? 'admin:plugins:deactivate:no_with_msg' : 'admin:plugins:deactivate:no'; register_error(elgg_echo($string, array($plugin->getFriendlyName(), $plugin->getError()))); } else { system_message("Plugin {$plugin->getFriendlyName()} has been deactivated"); } } elgg_flush_caches(); }
/** * {@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"); } }
public function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $app = $this->getSilexApplication(); $jobs = $app['gearman.jobs']->jobs(); $jobs = array_values($jobs); if (!$jobs) { throw new Exception('No jobs'); } $opportunities = []; foreach ($jobs as $job) { $opportunities[] = '<comment>' . $job->getUUID() . '</comment> - <info>' . $job->getTask() . '</info> ' . $job->getWorkload(Job::WORKLOAD_JSON) . ($job->getResult() ? ' : <question>' . $job->getResult() . '</question>' : null); } $whichJob = new ChoiceQuestion('Which job do you want to delete ? (separated by coma)', $opportunities, null); $whichJob->setMultiselect(true); $answers = $helper->ask($input, $output, $whichJob); foreach ($answers as $answer) { $key = array_search($answer, $opportunities); $app['gearman.jobs']->delete($jobs[$key]->getUUID()); $output->writeln('Job deleted : <info>' . $jobs[$key]->getUUID() . '</info>'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $userService = new UserService($this->getSlim()); $helper = $this->getHelper('question'); if (null === $input->getOption('email')) { $question = new Question('Please enter an e-mail: ', 'untitled'); $email = $helper->ask($input, $output, $question); } else { $email = $input->getOption('email'); } if (null === $input->getOption('password')) { $question = new Question('Please enter a password: '******''); $password = $helper->ask($input, $output, $question); } else { $password = $input->getOption('password'); } $userService->fetchAvailablePermissions(); $permissionsDictionary = []; foreach ($userService->getCursor() as $permission) { $permissionsDictionary[$permission->getName()] = $permission; } if (null === $input->getOption('permissions')) { $question = new ChoiceQuestion('Please select which permissions you would like to enable (defaults to super). Separate multiple values with commas (without spaces). If you select super, all other permissions are also inherited: ', array_keys($permissionsDictionary), '0'); $question->setMultiselect(true); $selectedPermissionNames = $helper->ask($input, $output, $question); } else { $selectedPermissionNames = explode(',', $input->getOption('permissions')); } $selectedPermissions = []; foreach ($selectedPermissionNames as $selectedPermissionName) { $selectedPermissions[] = $permissionsDictionary[$selectedPermissionName]; } $user = $userService->addUser($email, $password, $selectedPermissions); $text = json_encode($user, JSON_PRETTY_PRINT); $output->writeln('<info>User successfully created!</info>'); $output->writeln('<info>Info:</info>'); $output->writeln($text); }
protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $context = $container->get('router')->getContext(); $context->setHost($container->getParameter('shivas_bouncer.bounce_endpoint')['host']); $context->setScheme($container->getParameter('shivas_bouncer.bounce_endpoint')['protocol']); $apiFactory = $container->get('shivas_bouncer.aws.client.factory'); $sesClient = $apiFactory->getSesClient(); $snsClient = $apiFactory->getSnsClient(); // fetch identities $response = $sesClient->listIdentities(); $identities = $response->get('Identities'); $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Please select identities to hook to: (comma separated numbers, default: all)', $identities, implode(",", range(0, count($identities) - 1, 1))); $question->setMultiselect(true); $selectedIdentities = $helper->ask($input, $output, $question); // create SNS topic $topic = array('Name' => $input->getArgument('name')); $response = $snsClient->createTopic($topic); $topicArn = $response->get('TopicArn'); /** @var TopicRepositoryInterface $topicRepo */ $topicRepo = $container->get('shivas_bouncer.object_manager')->getRepository('ShivasBouncerBundle:Topic'); $topicRepo->save(new Topic($topicArn)); $output->writeln("\nTopic created: " . $topicArn . "\n"); // subscribe selected SES identities to SNS topic $output->writeln(sprintf('Registering <comment>"%s"</comment> topic for identities:', $topic['Name'])); foreach ($selectedIdentities as $identity) { $output->write($identity . ' ... '); $sesClient->setIdentityNotificationTopic(array('Identity' => $identity, 'NotificationType' => 'Bounce', 'SnsTopic' => $topicArn)); $output->writeln('OK'); } $subscribe = ['TopicArn' => $topicArn, 'Protocol' => $container->getParameter('shivas_bouncer.bounce_endpoint')['protocol'], 'Endpoint' => $this->getContainer()->get('router')->generate($container->getParameter('shivas_bouncer.bounce_endpoint')['route_name'], array(), RouterInterface::ABSOLUTE_URL)]; $response = $snsClient->subscribe($subscribe); $output->writeln(sprintf("\nSubscription endpoint URI: <comment>%s</comment>\n", $subscribe['Endpoint'])); $output->writeln(sprintf("Subscription status: <comment>%s</comment>", $response->get('SubscriptionArn'))); }
/** * This method will ask the developer for it's input and will result in a configuration array. * * @param InputInterface $input * @param OutputInterface $output * * @return array */ protected function buildConfiguration(InputInterface $input, OutputInterface $output) { /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); $questionString = $this->createQuestionString('No grumphp.yml file could be found. Do you want to create one?', 'Yes'); $question = new ConfirmationQuestion($questionString, true); if (!$helper->ask($input, $output, $question)) { return array(); } // Search for git_dir $default = $this->guessGitDir(); $questionString = $this->createQuestionString('In which folder is GIT initialized?', $default); $question = new Question($questionString, $default); $question->setValidator(array($this, 'pathValidator')); $gitDir = $helper->ask($input, $output, $question); // Search for bin_dir $default = $this->guessBinDir(); $questionString = $this->createQuestionString('Where can we find the executables?', $default); $question = new Question($questionString, $default); $question->setValidator(array($this, 'pathValidator')); $binDir = $helper->ask($input, $output, $question); // Search tasks $question = new ChoiceQuestion('Which tasks do you want to run?', $this->getAvailableTasks(), array()); $question->setMultiselect(true); $tasks = $helper->ask($input, $output, $question); // Build configuration return array('parameters' => array('git_dir' => $gitDir, 'bin_dir' => $binDir, 'tasks' => array_map(function ($task) { return null; }, array_flip($tasks)))); }
/** * @param bool $multiselect */ public function setMultiselect($multiselect) { $this->_multiselect = $multiselect; return parent::setMultiselect($multiselect); }
/** * Executes the command. * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $email = $input->getArgument('email'); $firstname = $input->getArgument('firstname'); $lastname = $input->getArgument('lastname'); $password = $input->getArgument('password'); $usertype = $input->getArgument('usertype'); $developper = $input->getArgument('developper'); $userroles = $input->getArgument('userroles'); $dbService = $this->getContainer()->get('nyrocms_db'); $userTypes = $this->getContainer()->get('nyrocms_admin')->getUserTypeChoices(); $userRolesDb = $this->getContainer()->get('nyrocms_admin')->getUserRoles(); $helper = $this->getHelper('question'); if (!$email) { $question = new Question('Please enter the email of the user: '******'Please enter the firstname of the user: '******'Please enter the lastname of the user: '******'Please enter the password of the user: '******' doesn\'t exists'); $usertype = null; } if (!$usertype) { $question = new ChoiceQuestion('User type for the user?', $userTypes); $usertype = $helper->ask($input, $output, $question); } if (is_null($developper)) { $question = new ChoiceQuestion('Is developper?', array('false', 'true'), 0); $developper = $helper->ask($input, $output, $question); } if ($userroles) { $userroles = explode(',', $userroles); $tmp = array(); $error = false; foreach ($userroles as $id) { if (isset($userRolesDb[$id])) { $tmp[] = $id; } else { $output->writeln('User role ' . $id . ' doesn\'t exists'); $error = true; } } if (!$error) { $userroles = $tmp; } else { $userroles = array(); } } if (count($userroles) === 0 && count($userRolesDb) > 0) { $userRolesDbList = array('0' => 'nothing'); foreach ($userRolesDb as $id => $tmp) { $userRolesDbList[$id] = $id . ' - ' . $tmp . ''; } $question = new ChoiceQuestion('User roles for the user?', $userRolesDbList, '0'); $question->setMultiselect(true); $tmp = $helper->ask($input, $output, $question); foreach ($tmp as $tmp2) { $tmp2 = explode(' - ', $tmp2); $userroles[] = $tmp2[0]; } } $newUser = $dbService->getNew('user'); /* @var $newUser \NyroDev\NyroCmsBundle\Model\User */ $newUser->setEmail($email); $newUser->setFirstname($firstname); $newUser->setLastname($lastname); $salt = sha1(uniqid()); $passwordSalted = $this->getContainer()->get('security.encoder_factory')->getEncoder($newUser)->encodePassword($password, $salt); $newUser->setPassword($passwordSalted); $newUser->setSalt($salt); $newUser->setUserType($usertype); $newUser->setDevelopper($developper === 'true'); if (count($userroles)) { foreach ($userroles as $ur) { if (isset($userRolesDb[$ur])) { $newUser->addUserRole($userRolesDb[$ur]); } } } $dbService->flush(); $output->writeln('New user "' . $email . '" added with ID: ' . $newUser->getId()); }
/** * Give the user a single choice from an array of answers. * * @param string $question The question to ask to the user * @param array $choices The list of available choices * @param mixed $default The default answer to return * @param mixed $attempts * @param bool $multiple * * @return mixed */ public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null) { $question = new ChoiceQuestion("<question>{$question}</question> ", $choices, $default); $question->setMultiselect($multiple)->setMaxAttempts($attempts); return $this->getHelper('question')->ask($this->input, $this->output, $question); }
protected function interact(InputInterface $input, OutputInterface $output) { $dialog = $this->getDialogHelper(); $stringUtils = $this->getStringUtils(); // --module option $module = $input->getOption('module'); if (!$module) { // @see Drupal\AppConsole\Command\Helper\ModuleTrait::moduleQuestion $module = $this->moduleQuestion($output, $dialog); } $input->setOption('module', $module); // --class-name option $class_name = $input->getOption('class-name'); if (!$class_name) { $class_name = $dialog->askAndValidate($output, $dialog->getQuestion($this->trans('commands.generate.plugin.rest.resource.questions.class-name'), 'DefaultRestResource'), function ($value) use($stringUtils) { if (!strlen(trim($value))) { throw new \Exception('The Class name can not be empty'); } return $stringUtils->humanToCamelCase($value); }, false, 'DefaultRestResource'); } $input->setOption('class-name', $class_name); $machine_name = $stringUtils->camelCaseToUnderscore($class_name); // --plugin-label option $plugin_id = $input->getOption('plugin-id'); if (!$plugin_id) { $plugin_id = $dialog->ask($output, $dialog->getQuestion($this->trans('commands.generate.plugin.rest.resource.questions.plugin-id'), $machine_name), $machine_name); } $input->setOption('plugin-id', $plugin_id); // --plugin-id option $plugin_label = $input->getOption('plugin-label'); if (!$plugin_label) { $plugin_label = $dialog->ask($output, $dialog->getQuestion($this->trans('commands.generate.plugin.rest.resource.questions.plugin-label'), $machine_name), $machine_name); } $input->setOption('plugin-label', $plugin_label); // --plugin-url option $plugin_url = $input->getOption('plugin-url'); if (!$plugin_url) { $plugin_url = $dialog->ask($output, $dialog->getQuestion($this->trans('commands.generate.plugin.rest.resource.questions.plugin-url'), $machine_name), $machine_name); } $input->setOption('plugin-url', $plugin_url); // --plugin-states option $plugin_states = $input->getOption('plugin-states'); if (!$plugin_states) { $questionHelper = $this->getQuestionHelper(); $question = new ChoiceQuestion($this->trans('commands.generate.plugin.rest.resource.questions.plugin-states'), array('GET', 'PUT', 'POST', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'), '0'); $question->setMultiselect(true); $plugin_states = $questionHelper->ask($input, $output, $question); $output->writeln($this->trans('commands.generate.plugin.rest.resource.messages.selected-states') . ' ' . implode(', ', $plugin_states)); $input->setOption('plugin-states', $plugin_states); } }
/** * Interacts with the user. * * @param InputInterface $input The input * @param OutputInterface $output The output * * @throws \InvalidArgumentException * * @return void */ protected function interact(InputInterface $input, OutputInterface $output) { if (!$input->getArgument('username')) { $question = new Question('Please choose a username:'******'Username can not be empty'); } return $username; }); $username = $this->getHelper('question')->ask($input, $output, $question); $input->setArgument('username', $username); } if (!$input->getArgument('email')) { $question = new Question('Please choose an email:'); $question->setValidator(function ($email) { //TODO: we might want to check if its an actual email address ..? if (null === $email) { throw new \InvalidArgumentException('Email can not be empty'); } return $email; }); $email = $this->getHelper('question')->ask($input, $output, $question); $input->setArgument('email', $email); } if (!$input->getArgument('password')) { $question = new Question('Please choose a password:'******'Password can not be empty'); } return $password; }); $password = $this->getHelper('question')->ask($input, $output, $question); $input->setArgument('password', $password); } if (!$input->getArgument('locale')) { $locale = $this->getHelper('question')->ask($input, $output, new Question('Please enter the locale (or leave empty for default admin locale):')); $input->setArgument('locale', $locale); } $groups = $this->getContainer()->get('fos_user.group_manager')->findGroups(); if (!$input->getOption('group')) { $question = new ChoiceQuestion('Please enter the group(s) the user should be a member of (multiple possible, separated by comma):', $groups, ''); $question->setMultiselect(true); $question->setValidator(function ($groups) { if ($groups === '') { throw new \RuntimeException('Group(s) must be of type integer and can not be empty'); } return $groups; }); // Group has to be imploded because $input->setOption expects a string $groups = $this->getHelper('question')->ask($input, $output, $question); $input->setOption('group', $groups); } }
/** * Asks the user which sitemaps from Magento's sitemap collection to process. * @param InputInterface $input * @param OutputInterface $output * @return array|bool */ protected function askSitemapsToProcess(InputInterface $input, OutputInterface $output) { $sitemapCollection = $this->retrieveSitemaps(); if (!$sitemapCollection) { $output->writeln('<error>There are no sitemaps defined in Magento\'s sitemap collection.</error>'); return false; } $this->getHelper('table')->setHeaders(array('Store ID', 'Active', 'Store code', 'Path', 'Generated', 'Store URL'))->renderByFormat($output, $sitemapCollection); $helper = $this->getHelper('question'); $question = new ChoiceQuestion('<question>Please select one or more sitemaps. - use numbers, comma seperated for multi</question>', array_column($sitemapCollection, 'relative_path')); $question->setMultiselect(true); $answer = $helper->ask($input, $output, $question); foreach ($sitemapCollection as $sitemap) { if (in_array($sitemap['relative_path'], $answer)) { $sitemaps[] = $sitemap; } } return $sitemaps; }
/** * @param InputInterface $input * @param OutputInterface $output * @param array $allToolsNames * @param array $toolsNamesToExclude * * @return string * * @throws \RuntimeException If PHP tool is not found */ protected function askPhpToolName(InputInterface $input, OutputInterface $output, array $allToolsNames, array $toolsNamesToExclude = []) { $helper = $this->getHelper('question'); $choices = count($toolsNamesToExclude) ? array_values(array_diff($allToolsNames, $toolsNamesToExclude)) : $allToolsNames; if (count($choices) == 0) { $question = new ConfirmationQuestion('All PHP tools are already installed. Do you want force installation for all tools? (<info>y</info>/n; default do nothing) ', false); if (!$helper->ask($input, $output, $question)) { return []; } $output->writeln(' '); return $allToolsNames; } $default = implode(',', $choices); $question = new ChoiceQuestion('Please select what PHP tool to install (defaults to all names; separate multiple names with a comma; autocompletion is active)', $choices, $default); $question->setMultiselect(true); $names = $helper->ask($input, $output, $question); $output->writeln('You have just selected: <info>' . implode(', ', $names) . '</info>'); return $names; }