protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $show_installed = !$input->getOption('available'); $installed = $available = array(); foreach ($this->load_migrations() as $name) { if ($this->migrator->migration_state($name) !== false) { $installed[] = $name; } else { $available[] = $name; } } if ($show_installed) { $io->section($this->user->lang('CLI_MIGRATIONS_INSTALLED')); if (!empty($installed)) { $io->listing($installed); } else { $io->text($this->user->lang('CLI_MIGRATIONS_EMPTY')); $io->newLine(); } } $io->section($this->user->lang('CLI_MIGRATIONS_AVAILABLE')); if (!empty($available)) { $io->listing($available); } else { $io->text($this->user->lang('CLI_MIGRATIONS_EMPTY')); $io->newLine(); } }
private function printMiddlewares() { if (!$this->configuration->getMiddlewares()) { return; } $this->title('Middlewares'); $this->output->listing($this->configuration->getMiddlewares()); }
/** * {@inheritdoc} */ protected function executeLocked(InputInterface $input, OutputInterface $output) { $this->fs = new Filesystem(); $this->io = new SymfonyStyle($input, $output); $this->rootDir = dirname($this->getContainer()->getParameter('kernel.root_dir')); $this->addEmptyDirs(); $this->addIgnoredDirs(); if (!empty($this->rows)) { $this->io->newLine(); $this->io->listing($this->rows); } $this->addInitializePhp(); return 0; }
/** * Executes the command reparser:list * * @param InputInterface $input * @param OutputInterface $output * @return integer */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $io->section($this->user->lang('CLI_DESCRIPTION_REPARSER_AVAILABLE')); $io->listing($this->reparser_names); return 0; }
/** * @param SymfonyStyle|null $io */ public function updateCode(SymfonyStyle $io = null) { $io->title('CampaignChain Data Update'); if (empty($this->versions)) { $io->warning('No code updater Service found, maybe you didn\'t enable a bundle?'); return; } $io->comment('The following data versions will be updated'); $migratedVersions = array_map(function (DataUpdateVersion $version) { return $version->getVersion(); }, $this->em->getRepository('CampaignChainUpdateBundle:DataUpdateVersion')->findAll()); $updated = false; foreach ($this->versions as $version => $class) { if (in_array($version, $migratedVersions)) { continue; } $io->section('Version ' . $class->getVersion()); $io->listing($class->getDescription()); $io->text('Begin data update'); $result = $class->execute($io); if ($result) { $dbVersion = new DataUpdateVersion(); $dbVersion->setVersion($version); $this->em->persist($dbVersion); $this->em->flush(); $io->text('Data update finished'); } $updated = true; } if (!$updated) { $io->success('All data is up to date.'); } else { $io->success('Every data version has been updated.'); } }
/** * If the user does not specify the $name parameter, then we will * prompt for it here. * * @hook interact * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ public function interact(InputInterface $input, OutputInterface $output) { $available_art = $this->availableArt(); $io = new SymfonyStyle($input, $output); $art_name = $input->getArgument('name'); if (!$art_name) { $io->title('Available Art'); $io->listing($available_art); } }
/** * Summarize changes since last tag. */ protected function summarizeCommits() { $last = $this->changelog->getLastRelease(); if (!$last) { return; } $commits = $this->executeQuietly(['git', 'log', $last['name'] . '..HEAD', '--oneline']); $commits = explode(PHP_EOL, trim($commits)); if (!$commits) { $this->output->writeln('Commits since <comment>' . $last['name'] . '</comment>:'); $this->output->listing($commits); } }
private function showLocaleOverview() { $locale = array_map(function ($locale, $key) { $enabledMessage = null; $interfaceMessage = null; if ($this->defaultEnabledLocale === $key) { $enabledMessage = ' (default)'; } if ($this->defaultInterfaceLocale === $key) { $interfaceMessage = ' (default)'; } return ['key' => $key, 'locale' => $locale, 'installed' => array_key_exists($key, $this->installedLocale) ? 'Y' : 'N', 'interface' => (array_key_exists($key, $this->interfaceLocale) ? 'Y' : 'N') . $interfaceMessage, 'enabled' => (array_key_exists($key, $this->enabledLocale) ? 'Y' : 'N') . $enabledMessage, 'redirect' => array_key_exists($key, $this->redirectLocale) ? 'Y' : 'N']; }, $this->getInstallableLocale(), array_keys($this->getInstallableLocale())); $this->formatter->listing(["key:\t\tThe identifier of the locale", "locale:\tThe name of the locale", "installed:\tPossible locale to use as interface, enabled or redirect locale", "interface:\tLocale that the user in the backend can use for the interface", "enabled:\tLocale that are accessible for visitors", "redirect:\tLocale that people may automatically be redirected to based upon their browser locale"]); $this->formatter->table(['key', 'locale', 'installed', 'interface', 'enabled', 'redirect'], $locale); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $file = $input->getOption('config') ?: sprintf('%s/pbjc.yml', getcwd()); if (!file_exists($file)) { $io->error(sprintf('File "%s" does not exists.', $file)); return; } $parser = new Parser(); $data = $parser->parse(file_get_contents($file)); if (!is_array($data['namespaces'])) { $data['namespaces'] = [$data['namespaces']]; } $io->title('Generated files for namespaces:'); $io->listing($data['namespaces']); // output callback $callback = function (OutputFile $file) use($io) { $io->text($file->getFile()); if (!is_dir(dirname($file->getFile()))) { mkdir(dirname($file->getFile()), 0777, true); } file_put_contents($file->getFile(), $file->getContents()); }; $languages = []; if (isset($data['languages'])) { $languages = $data['languages']; unset($data['languages']); } $compile = new Compiler(); foreach ($languages as $language => $options) { if ($input->getOption('language') && $input->getOption('language') != $language) { continue; } $options = array_merge($data, $options, ['callback' => $callback]); try { $io->section($language); $compile->run($language, new CompileOptions($options)); $io->success("👍"); //thumbs-up-sign } catch (\Exception $e) { $io->error($e->getMessage()); } } }
/** * Displays a security report as plain text. * * @param OutputInterface $output * @param string $lockFilePath The file path to the checked lock file * @param array $vulnerabilities An array of vulnerabilities */ public function displayResults(OutputInterface $output, $lockFilePath, array $vulnerabilities) { $output = new SymfonyStyle(new ArrayInput(array()), $output); $output->title('Symfony Security Check Report'); $output->comment(sprintf('Checked file: <comment>%s</>', realpath($lockFilePath))); if ($count = count($vulnerabilities)) { $output->error(sprintf('%d packages have known vulnerabilities.', $count)); } else { $output->success('No packages have known vulnerabilities.'); } if (0 !== $count) { foreach ($vulnerabilities as $dependency => $issues) { $output->section(sprintf('%s (%s)', $dependency, $issues['version'])); $details = array_map(function ($value) { return sprintf("<info>%s</>: %s\n %s", $value['cve'] ?: '(no CVE ID)', $value['title'], $value['link']); }, $issues['advisories']); $output->listing($details); } } $output->note('This checker can only detect vulnerabilities that are referenced in the SensioLabs security advisories database. Execute this command regularly to check the newly discovered vulnerabilities.'); }
/** * @param SymfonyStyle|null $io * @param bool $updateDatabase * * @return bool * * @throws \Doctrine\DBAL\ConnectionException * @throws \Exception */ public function install(SymfonyStyle $io = null) { $this->logger->info('START: MODULES INSTALLER'); $newBundles = $this->bundleConfigService->getNewBundles(); if (empty($newBundles)) { if ($io) { $io->success('No new modules found.'); } $this->logger->info('No new modules found.'); $this->logger->info('END: MODULES INSTALLER'); return false; } // Increase timeout limit to run this script. set_time_limit(240); $this->kernelService->parseBundlesForKernelConfig($newBundles); $loggerResult = ''; $this->em->getConnection()->beginTransaction(); $this->registerDistribution(); try { foreach ($newBundles as $newBundle) { switch ($newBundle->getType()) { case 'campaignchain-core': break; case 'campaignchain-hook': // TODO: new vs. update $this->registerHook($newBundle); break; case 'campaignchain-symfony': $this->registerSymfonyBundle($newBundle); break; default: $this->registerModule($newBundle); break; } $loggerResult .= $newBundle->getName() . ', '; $this->em->persist($newBundle); } $this->em->flush(); // Store the campaign types a campaign can be copied to. $this->registerCampaignConversions(); // Store the channels related to an activity or Location. $this->registerChannelRelationships(); // Store the system parameters injected by modules. $this->registerModuleSystemParams(); // Register any new Bundles in the Symfony kernel. $this->kernelService->register(); $this->em->getConnection()->commit(); } catch (\Exception $e) { $this->em->getConnection()->rollBack(); if ($io) { $io->error('Error at update: ' . $e->getMessage()); } $this->logger->error('Error: ' . $e->getMessage()); $this->logger->info('END: MODULES INSTALLER'); throw $e; } $this->logger->info('Installed/updated modules: ' . rtrim($loggerResult, ', ')); if ($io) { $io->section('Installed/updated modules:'); $io->listing(explode(', ', rtrim($loggerResult, ', '))); } $this->logger->info('END: MODULES INSTALLER'); return true; }
protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $twig = $this->getTwigEnvironment(); if (null === $twig) { $io->error('The Twig environment needs to be set.'); return 1; } $types = array('functions', 'filters', 'tests', 'globals'); if ($input->getOption('format') === 'json') { $data = array(); foreach ($types as $type) { foreach ($twig->{'get' . ucfirst($type)}() as $name => $entity) { $data[$type][$name] = $this->getMetadata($type, $entity); } } $data['tests'] = array_keys($data['tests']); $io->writeln(json_encode($data)); return 0; } $filter = $input->getArgument('filter'); foreach ($types as $index => $type) { $items = array(); foreach ($twig->{'get' . ucfirst($type)}() as $name => $entity) { if (!$filter || false !== strpos($name, $filter)) { $items[$name] = $name . $this->getPrettyMetadata($type, $entity); } } if (!$items) { continue; } $io->section(ucfirst($type)); ksort($items); $io->listing($items); } return 0; }
<?php use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; // Ensure has proper line ending before outputing a text block like with SymfonyStyle::listing() or SymfonyStyle::text() return function (InputInterface $input, OutputInterface $output) { $output = new SymfonyStyle($input, $output); $output->writeln('Lorem ipsum dolor sit amet'); $output->listing(array('Lorem ipsum dolor sit amet', 'consectetur adipiscing elit')); // Even using write: $output->write('Lorem ipsum dolor sit amet'); $output->listing(array('Lorem ipsum dolor sit amet', 'consectetur adipiscing elit')); $output->write('Lorem ipsum dolor sit amet'); $output->text(array('Lorem ipsum dolor sit amet', 'consectetur adipiscing elit')); };
/** * Executes the current command. * * This method is not abstract because you can use this class * as a concrete class. In this case, instead of defining the * execute() method, you set the code to execute by passing * a Closure to the setCode() method. * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance * * @return null|int null or 0 if everything went fine, or an error code * * @see setCode() */ protected function execute(InputInterface $input, OutputInterface $output) { $styleHelper = new SymfonyStyle($input, $output); $validatorFactory = new ValidatorFactoryImplementation(); $validators = $validatorFactory->getMessageValidator(); $commitMessage = file_get_contents($input->getArgument(self::ARGUMENT_COMMIT_MESSAGE_FILE)); $commentCharacter = $input->getOption(self::OPTION_COMMENT_CHAR); $ignorePatterns = $input->getOption(self::OPTION_IGNORE); foreach ($ignorePatterns as $ignorePattern) { if (preg_match($ignorePattern, $commitMessage)) { return 0; } } $safeCommitMessage = preg_replace('/' . preg_quote($commentCharacter) . '.*/', '', $commitMessage); $message = new MessageImplementation($safeCommitMessage); $validators->validate($message); if (count($message->getStatuses()) < 1) { return 0; } $statusList = []; $isPositive = true; /** @var Status $status */ foreach ($message->getStatuses() as $status) { $statusList[] = $status->getMessage() . ' (' . $status->getDetailsUrl() . ')'; $isPositive = $status->isPositive() && $isPositive; } if ($isPositive) { return 0; } $styleHelper->error('Incorrectly formatted commit message'); $styleHelper->listing($statusList); $styleHelper->section('Your Commit Message'); $styleHelper->block($commitMessage); $styleHelper->warning('A commit has not been created'); return 1; }
private function updateSchema(SymfonyStyle $io, $queries) { $io->caution("Your database schema needs to be updated. The following queries will be run:"); $io->listing($queries); if ($this->updateDb === false && $io->confirm("Should we run this queries now?", false) === false) { return; } $cmdOutput = new BufferedOutput(); $command = $this->getApplication()->find('doctrine:schema:update'); $force = new ArrayInput(array('--env' => 'dev', '--dump-sql' => true, '--force' => true)); $command->run($force, $cmdOutput); $result = $cmdOutput->fetch(); if (strstr($result, 'Database schema updated successfully!') === false) { $io->error("Couldn't update the schema. Run 'doctrine:schema:update' separately to find out why"); } $io->success("Database schema updated successfully!"); $this->clearMetadata($io); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); if (!($searchPaths = $input->getArgument('fixtures'))) { $searchPaths = $this->getSearchPaths(); } if (count($searchPaths) === 0) { $io->error('No search paths could be determinened.'); return; } $io->section('Determening ORM paths'); $io->listing($searchPaths); $io->section('Registering fixtures'); $registry = new FixtureRegistry($this->getContainer()); foreach ($searchPaths as $path) { $registry->loadFromPath($path); } $fixtures = $registry->getFixtures(); if (!$fixtures) { $io->error('Unable to find any fixtures within the following search paths.'); $io->listing($searchPaths); return; } if ($input->isInteractive() && !$io->confirm('Do you want to begin fixture loading', false)) { return; } $purger = new ORMPurger($this->em); $purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE); $executor = new ORMExecutor($this->em, $purger); $executor->setLogger(function ($message) use($output) { $output->writeln(sprintf(' <comment>></comment> <info>%s</info>', $message)); }); $io->section('Importing fixtures'); $executor->execute($fixtures, true); $io->success('Complete!'); /* if ($input->isInteractive() && !$input->getOption('append')) { if (!$this->askConfirmation($input, $output, '<question>Careful, database will be purged. Do you want to continue y/N ?</question>', false)) { return; } } */ }
protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $types = []; $listing = []; // If no option selected, all are active. if (!$input->getOption('config-only') && !$input->getOption('routing-only') && !$input->getOption('class-only') && !$input->getOption('security-only')) { $input->setOption('config-only', true); $input->setOption('routing-only', true); $input->setOption('class-only', true); $input->setOption('security-only', true); } if ($input->getOption('class-only')) { $types = array_merge($types, ['classes' => true]); $listing[] = 'Registering bundle classes of all CampaignChain modules in AppKernel.php.'; } if ($input->getOption('config-only')) { $types = array_merge($types, ['configs' => true]); $listing[] = 'Registering config.yml files of all CampaignChain modules'; } if ($input->getOption('routing-only')) { $types = array_merge($types, ['routings' => true]); $listing[] = 'Registering routing.yml files of all CampaignChain modules'; } if ($input->getOption('security-only')) { $types = array_merge($types, ['security' => true]); $listing[] = 'Registering security.yml files of all CampaignChain modules'; } $kernelRootDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..'; $devEnv = true; if ($input->getOption('env') == 'prod') { $devEnv = false; } $packages = new Package($kernelRootDir, $devEnv); $locator = new BundleLocator($kernelRootDir, $packages); $availableBundles = $locator->getAvailableBundles(); $kernel = new Kernel($kernelRootDir); $kernel->parseBundlesForKernelConfig($availableBundles); $io->listing($listing); $kernel->register($types); $io->success('CampaignChain modules configuration files are updated'); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output = new SymfonyStyle($input, $output); $kernel = $this->getContainer()->get('kernel'); // check presence of force or dump-message if ($input->getOption('force') !== true && $input->getOption('dump-messages') !== true) { $output->error('You must choose one of --force or --dump-messages'); return 1; } // check format $writer = $this->getContainer()->get('translation.writer'); $supportedFormats = $writer->getFormats(); if (!in_array($input->getOption('output-format'), $supportedFormats)) { $output->error(array('Wrong output format', 'Supported formats are ' . implode(', ', $supportedFormats) . '.')); return 1; } $kernel = $this->getContainer()->get('kernel'); // Define Root Path to App folder $transPaths = array($kernel->getRootDir() . '/Resources/'); $currentName = 'app folder'; // Override with provided Bundle info if (null !== $input->getArgument('bundle')) { try { $foundBundle = $kernel->getBundle($input->getArgument('bundle')); $transPaths = array($foundBundle->getPath() . '/Resources/', sprintf('%s/Resources/%s/', $kernel->getRootDir(), $foundBundle->getName())); $currentName = $foundBundle->getName(); } catch (\InvalidArgumentException $e) { // such a bundle does not exist, so treat the argument as path $transPaths = array($input->getArgument('bundle') . '/Resources/'); $currentName = $transPaths[0]; if (!is_dir($transPaths[0])) { throw new \InvalidArgumentException(sprintf('<error>"%s" is neither an enabled bundle nor a directory.</error>', $transPaths[0])); } } } $output->title('Symfony translation update command'); $output->text(sprintf('Generating "<info>%s</info>" translation files for "<info>%s</info>"', $input->getArgument('locale'), $currentName)); // load any messages from templates $extractedCatalogue = new MessageCatalogue($input->getArgument('locale')); $output->text('Parsing templates'); $extractor = $this->getContainer()->get('translation.extractor'); $extractor->setPrefix($input->getOption('prefix')); foreach ($transPaths as $path) { $path .= 'views'; if (is_dir($path)) { $extractor->extract($path, $extractedCatalogue); } } // load any existing messages from the translation files $currentCatalogue = new MessageCatalogue($input->getArgument('locale')); $output->text('Loading translation files'); $loader = $this->getContainer()->get('translation.loader'); foreach ($transPaths as $path) { $path .= 'translations'; if (is_dir($path)) { $loader->loadMessages($path, $currentCatalogue); } } // process catalogues $operation = $input->getOption('clean') ? new DiffOperation($currentCatalogue, $extractedCatalogue) : new MergeOperation($currentCatalogue, $extractedCatalogue); // Exit if no messages found. if (!count($operation->getDomains())) { $output->warning('No translation found.'); return; } // show compiled list of messages if ($input->getOption('dump-messages') === true) { $output->newLine(); foreach ($operation->getDomains() as $domain) { $output->section(sprintf('Displaying messages for domain <info>%s</info>:', $domain)); $newKeys = array_keys($operation->getNewMessages($domain)); $allKeys = array_keys($operation->getMessages($domain)); $output->listing(array_merge(array_diff($allKeys, $newKeys), array_map(function ($id) { return sprintf('<fg=green>%s</>', $id); }, $newKeys), array_map(function ($id) { return sprintf('<fg=red>%s</>', $id); }, array_keys($operation->getObsoleteMessages($domain))))); } if ($input->getOption('output-format') == 'xlf') { $output->writeln('Xliff output version is <info>1.2</info>'); } } if ($input->getOption('no-backup') === true) { $writer->disableBackup(); } // save the files if ($input->getOption('force') === true) { $output->text('Writing files'); $bundleTransPath = false; foreach ($transPaths as $path) { $path .= 'translations'; if (is_dir($path)) { $bundleTransPath = $path; } } if ($bundleTransPath) { $writer->writeTranslations($operation->getResult(), $input->getOption('output-format'), array('path' => $bundleTransPath, 'default_locale' => $this->getContainer()->getParameter('kernel.default_locale'))); } } $output->newLine(); $output->success('Success'); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->initializeVariables(); $this->io = new SymfonyStyle($input, $output); $this->io->title('CampaignChain Scheduler'); // Prevent multiple console runs $lock = new LockHandler('campaignchain:scheduler'); if (!$lock->lock()) { $this->io->error('The command is already in another process.'); return 0; } $this->scheduler = $this->startScheduler(); $this->logger->info(self::LOGGER_MSG_START); $this->logger->info('Scheduler with ID {id} started', ['id' => $this->scheduler->getId()]); $this->io->text('Running scheduler with:'); $this->io->listing(['Scheduler ID: ' . $this->scheduler->getId(), 'Interval: ' . $this->scheduler->getPeriodInterval() . ' minute(s)', 'Period starts: ' . $this->scheduler->getPeriodStart()->format('Y-m-d H:i:s T'), 'Period ends: ' . $this->scheduler->getPeriodEnd()->format('Y-m-d H:i:s T')]); //Que jobs $this->gatherActionData(); // Execute the scheduled report jobs. $this->prepareReportJobs(); $this->executeJobs(); // Scheduler is done, let's see how long it took. $stopwatchSchedulerEvent = $this->stopwatchScheduler->stop('scheduler'); $this->scheduler->setDuration($stopwatchSchedulerEvent->getDuration()); $this->scheduler->setExecutionEnd($this->now); $this->scheduler->setStatus(Scheduler::STATUS_CLOSED); $this->em->persist($this->scheduler); $this->em->flush(); $this->io->success('Duration of scheduler: ' . $stopwatchSchedulerEvent->getDuration() . ' milliseconds'); $this->logger->info(self::LOGGER_MSG_END); }