text() public method

public text ( $message )
Esempio n. 1
0
 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();
     }
 }
Esempio n. 2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // throw new \Exception('boo');
     $directory = realpath($input->getArgument('directory'));
     $directoryOutput = $input->getArgument('outputdirectory');
     /* @var $logger Psr\Log\LoggerInterface */
     $this->logger = $this->getContainer()->get('logger');
     $io = new SymfonyStyle($input, $output);
     $io->title('DDD Model Generation');
     $clean = $input->hasOption('clean');
     if ($clean) {
         $io->section('Clean output directoty');
         $fs = new \Symfony\Component\Filesystem\Filesystem();
         try {
             $fs->remove($directoryOutput);
         } catch (IOExceptionInterface $e) {
             $io->error($e->getMessage());
         }
         $io->text('clean of ' . $directoryOutput . ' completed');
     }
     if (is_dir($directory)) {
         $finder = new Finder();
         $finder->search($directory);
         foreach ($finder->getFindedFiles() as $file) {
             if (pathinfo($file, PATHINFO_FILENAME) == 'model.yml') {
                 $io->text('Analizzo model.yml in ' . pathinfo($file, PATHINFO_DIRNAME));
                 $dddGenerator = new DDDGenerator();
                 $dddGenerator->setLogger($this->logger);
                 $dddGenerator->analyze($file);
                 $dddGenerator->generate($directoryOutput);
             }
         }
         $io->section('Php-Cs-Fixer on generated files');
         $fixer = new \Symfony\CS\Console\Command\FixCommand();
         $input = new ArrayInput(['path' => $directoryOutput, '--level' => 'psr2', '--fixers' => 'eof_ending,strict_param,short_array_syntax,trailing_spaces,indentation,line_after_namespace,php_closing_tag']);
         $output = new BufferedOutput();
         $fixer->run($input, $output);
         $content = $output->fetch();
         $io->text($content);
         if (count($this->errors) == 0) {
             $io->success('Completed generation');
         } else {
             $io->error($this->errors);
         }
     } else {
         $io->caution('Directory ' . $directory . ' not valid');
     }
     // PER I WARNING RECUPERABILI
     //$io->note('Generate Class');
 }
Esempio n. 3
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->io->title($this->getDescription());
     $this->io->text("removing articles\n");
     $this->removeArticles();
     $this->io->newLine(2);
     $this->io->text("refresh journal and remove issues\n");
     $this->removeIssues($input);
     $this->io->newLine(1);
     $this->io->text("refresh journal and remove journal totally");
     $this->refreshJournal($input);
     $this->em->remove($this->journal);
     $this->em->flush();
     $this->io->success('successfully removed journal');
 }
Esempio n. 4
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $router = $this->getContainer()->get('router');
     $context = $router->getContext();
     if (null !== ($method = $input->getOption('method'))) {
         $context->setMethod($method);
     }
     if (null !== ($scheme = $input->getOption('scheme'))) {
         $context->setScheme($scheme);
     }
     if (null !== ($host = $input->getOption('host'))) {
         $context->setHost($host);
     }
     $matcher = new TraceableUrlMatcher($router->getRouteCollection(), $context);
     $traces = $matcher->getTraces($input->getArgument('path_info'));
     $io->newLine();
     $matches = false;
     foreach ($traces as $trace) {
         if (TraceableUrlMatcher::ROUTE_ALMOST_MATCHES == $trace['level']) {
             $io->text(sprintf('Route <info>"%s"</> almost matches but %s', $trace['name'], lcfirst($trace['log'])));
         } elseif (TraceableUrlMatcher::ROUTE_MATCHES == $trace['level']) {
             $io->success(sprintf('Route "%s" matches', $trace['name']));
             $routerDebugCommand = $this->getApplication()->find('debug:router');
             $routerDebugCommand->run(new ArrayInput(array('name' => $trace['name'])), $output);
             $matches = true;
         } elseif ($input->getOption('verbose')) {
             $io->text(sprintf('Route "%s" does not match: %s', $trace['name'], $trace['log']));
         }
     }
     if (!$matches) {
         $io->error(sprintf('None of the routes match the path "%s"', $input->getArgument('path_info')));
         return 1;
     }
 }
Esempio n. 5
0
 private function updateModules()
 {
     $this->output->text('Attempting to updating modules');
     /** @var EntityManager|DocumentManager $manager */
     $manager = $this->getContainer()->get('default_manager');
     $repo = $manager->getRepository('App:Module');
     foreach ($this->getContainer()->getParameter('kernel.modules') as $module) {
         if (empty($repo->findOneBy(['name' => $module::getModuleName()]))) {
             $this->output->text('New module discovered. Adding to database.');
             $this->addModule($module);
         }
     }
     /** @var Module[] $modules */
     $modules = $manager->getRepository('App:Module')->findAll();
     /** @var Server[] $servers */
     $servers = $manager->getRepository($this->getContainer()->getParameter('server_class'))->findAll();
     foreach ($servers as $server) {
         foreach ($modules as $module) {
             if (!$server->hasModule($module)) {
                 $serverModule = new ServerModule();
                 $serverModule->setModule($module);
                 $serverModule->setServer($server);
                 $serverModule->setEnabled($module->getDefaultEnabled());
                 $manager->persist($serverModule);
                 $server->addModule($serverModule);
                 $manager->persist($server);
             }
         }
     }
     $manager->flush();
 }
    /**
     * Adds the initialize.php file.
     */
    private function addInitializePhp()
    {
        $this->fs->dumpFile($this->rootDir . '/system/initialize.php', <<<'EOF'
<?php

use Contao\CoreBundle\Response\InitializeControllerResponse;
use Symfony\Component\HttpFoundation\Request;

if (!defined('TL_SCRIPT')) {
    die('Your script is not compatible with Contao 4.');
}

/**
 * @var Composer\Autoload\ClassLoader
 */
$loader = require __DIR__ . '/../app/autoload.php';
include_once __DIR__ . '/../app/bootstrap.php.cache';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

$response = $kernel->handle(Request::create('/_contao/initialize', 'GET', [], [], [], $_SERVER));

// Send the response if not generated by the InitializeController
if (!($response instanceof InitializeControllerResponse)) {
    $response->send();
    $kernel->terminate($request, $response);
    exit;
}

EOF
);
        $this->io->text("Added/updated the <comment>system/initialize.php</comment> file.\n");
    }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->title('Exporting databases');
     $io->section('Exporting all databases');
     $strategies = $this->collectorDbStrategy->collectDatabasesStrategies();
     $totalStrategies = count($strategies);
     $io->writeln($totalStrategies . ' strategie(s) found.');
     $progressBar = new ProgressBar($output, $totalStrategies);
     $progressBar->setFormat(self::PROGRESS_BAR_FORMAT);
     $progressBar->setMessage('Beginning backuping');
     $this->eventDispatcher->dispatch(Events::BACKUP_BEGINS, new BackupBeginsEvent($output));
     $progressBar->start();
     $reportContent = new \ArrayObject();
     foreach ($strategies as $strategy) {
         $strategyIdentifier = $strategy->getIdentifier();
         $setProgressBarMessage = function ($message) use($progressBar, $strategyIdentifier) {
             $message = "[{$strategyIdentifier}] {$message}";
             $progressBar->setMessage($message);
             $progressBar->display();
         };
         $exportedFiles = $this->processorDatabaseDumper->dump($strategy, $setProgressBarMessage);
         $reportContent->append("Backuping of the database: {$strategyIdentifier}");
         foreach ($exportedFiles as $file) {
             $filename = $file->getPath();
             $reportContent->append("\t→ {$filename}");
         }
         $progressBar->advance();
     }
     $progressBar->finish();
     $io->newLine(2);
     $io->section('Report');
     $io->text($reportContent->getArrayCopy());
     $this->eventDispatcher->dispatch(Events::BACKUP_ENDS, new BackupEndsEvent($output));
 }
 public function execute(SymfonyStyle $io = null)
 {
     $currentProfiles = $this->em->getRepository('CampaignChainLocationGoogleAnalyticsBundle:Profile')->findAll();
     if (empty($currentProfiles)) {
         $io->text('There is no Profile entity to update');
         return true;
     }
     foreach ($currentProfiles as $profile) {
         if (substr($profile->getProfileId(), 0, 2) != 'UA') {
             continue;
         }
         $profile->setPropertyId($profile->getProfileId());
         $gaProfileUrl = $profile->getLocation()->getUrl();
         $google_base_url = 'https:\\/\\/www.google.com\\/analytics\\/web\\/#report\\/visitors-overview\\/a' . $profile->getAccountId() . 'w\\d+p';
         $pattern = '/' . $google_base_url . '(.*)/';
         preg_match($pattern, $gaProfileUrl, $matches);
         if (!empty($matches) && count($matches) == 2) {
             $profile->setProfileId($matches[1]);
             $profile->setIdentifier($profile->getProfileId());
         }
         $this->em->persist($profile);
     }
     $this->em->flush();
     return true;
 }
Esempio n. 9
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.');
     }
 }
Esempio n. 10
0
 /**
  * Outputs the handler that has been applied (resolved), but
  * only if the given handler is not the same as the last
  * handler.
  *
  * @param \Aedart\Scaffold\Contracts\Handlers\Handler $handler
  */
 protected function outputAppliedHandler($handler)
 {
     $handlerClass = get_class($handler);
     if ($handlerClass != $this->lastHandler) {
         $this->lastHandler = $handlerClass;
         $this->output->text("Using handler: {$handlerClass}");
     }
 }
Esempio n. 11
0
 /**
  * @param Journal $journal
  * @return bool|null
  */
 private function normalizeLastIssuesByJournal(Journal $journal)
 {
     $this->io->newLine();
     $this->io->text('normalizing last issue for ' . $journal->getTitle());
     $this->io->progressAdvance();
     $findLastIssue = $this->em->getRepository('OjsJournalBundle:Issue')->findOneBy(['journal' => $journal, 'lastIssue' => true]);
     if ($findLastIssue) {
         return true;
     }
     /** @var Issue|null $getLogicalLastIssue */
     $getLogicalLastIssue = $this->em->getRepository('OjsJournalBundle:Issue')->getLastIssueByJournal($journal);
     if ($getLogicalLastIssue == null) {
         return null;
     }
     $getLogicalLastIssue->setLastIssue(true);
     $this->em->flush();
 }
Esempio n. 12
0
 /**
  * @param Bundle[] $bundles
  *
  * @return Bundle|null
  */
 private function selectBundle(array $bundles)
 {
     $packageNames = array_map(function (Bundle $bundle) {
         return $bundle->getName();
     }, $bundles);
     $selectedName = $this->io->choice('Please select the package, where you want to place the Migration file', $packageNames, $this->getContainer()->getParameter('campaignchain_update.diff_package'));
     $this->io->text('You have selected: ' . $selectedName);
     $selectedBundle = null;
     foreach ($bundles as $bundle) {
         if ($bundle->getName() != $selectedName) {
             continue;
         }
         $selectedBundle = $bundle;
         break;
     }
     return $selectedBundle;
 }
Esempio n. 13
0
 /**
  * @return bool|null
  */
 private function validateEntities()
 {
     $this->io->newLine();
     $this->io->text('Validation Starting for all entities');
     $metas = $this->em->getMetadataFactory()->getAllMetadata();
     /** @var ClassMetadata $meta */
     foreach ($metas as $meta) {
         if ($meta->isMappedSuperclass) {
             continue;
         }
         $reflClass = $meta->getReflectionClass();
         if ($reflClass->hasMethod('__toString')) {
             $this->io->text(sprintf('%s %s -> have __toString function', $this->os->okSign(), $meta->getName()));
         } else {
             $this->io->text(sprintf('%s %s -> have not __toString function', $this->os->warningSign(), $meta->getName()));
         }
     }
 }
 protected function removeInstallationFiles()
 {
     $installfiles = array('install.php', 'install-frameworkmissing.html');
     foreach ($installfiles as $installfile) {
         if (file_exists($this->directory . '/' . $installfile)) {
             @unlink($this->directory . '/' . $installfile);
         }
         file_exists($this->directory . '/' . $installfile) ? $this->io->warning('Could not delete file : ' . $installfile) : $this->io->text('Deleted installation file : ' . $installfile);
     }
 }
Esempio n. 15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $jwt = $this->getContainer()->get('jwt_coder');
     $username = $input->getArgument('username');
     if (!$username) {
         $username = $io->ask('Username');
     }
     $io->text('Token: ' . $jwt->encode(['username' => $username]));
     $io->success('JWT created');
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->io = new SymfonyStyle($input, $output);
     $this->sort = $input->getOption('sort');
     $this->sleepTime = $input->getOption('sleepTime');
     if (!$input->hasOption('sleepTime') && $output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) {
         $this->sleepTime = 25;
     }
     // Transform milliseconds in microseconds for usleep()
     $this->sleepTime = $this->sleepTime * 1000;
     $this->numberOfCodesToGenerate = $input->getOption('amount');
     // The length of each outputted code
     $this->codeLength = $input->getOption('length');
     // All possible chars. By default, 'A' to 'Z' and '0' to '9'
     $this->possibleChars = str_split($input->getOption('characters'));
     $baseNumberOfChars = count($this->possibleChars);
     $this->possibleChars = array_unique($this->possibleChars);
     // If there's an error here, we'll say it later
     $maxPossibleNumberOfCombinations = pow(count($this->possibleChars), $this->codeLength);
     if ($maxPossibleNumberOfCombinations < $this->numberOfCodesToGenerate) {
         $this->io->error(sprintf('Cannot generate %s combinations because there are only %s combinations possible', number_format($this->numberOfCodesToGenerate, 0, '', ' '), number_format($maxPossibleNumberOfCombinations, 0, '', ' ')));
         return 1;
     } else {
         $this->io->block(sprintf('Generating %s combinations.', number_format($this->numberOfCodesToGenerate, 0, '', ' ')), null, 'info');
         if ($maxPossibleNumberOfCombinations > $this->numberOfCodesToGenerate) {
             $this->io->block(sprintf('Note: If you need you can generate %s more combinations (with a maximum of %s).', number_format($maxPossibleNumberOfCombinations - $this->numberOfCodesToGenerate, 0, '', ' '), number_format($maxPossibleNumberOfCombinations, 0, '', ' ')), null, 'comment');
         }
     }
     $this->io->block('Available characters:');
     $this->io->block(implode('', $this->possibleChars), null, 'info');
     $codesList = $this->doGenerate();
     $outputFile = $input->getOption('output');
     if ($outputFile) {
         $save = true;
         if (file_exists($outputFile)) {
             $save = $this->io->confirm(sprintf('File %s exists. Erase it?', $outputFile), false);
         }
         if ($save) {
             $this->io->block(sprintf('Output results to %s', $outputFile), null, 'info');
             if (!file_put_contents($outputFile, implode("\n", $codesList))) {
                 throw new \Exception(sprintf('Could not write to %s...', $outputFile));
             }
         }
     } else {
         $this->io->text($codesList);
     }
     if ($baseNumberOfChars !== count($this->possibleChars)) {
         $this->io->warning(sprintf('We detected that there were duplicate characters in "%s", so we removed them.', $input->getOption('characters')));
     }
     return 0;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $username = $input->getArgument('username');
     $manager = $this->getContainer()->get('doctrine.orm.entity_manager');
     $user = $manager->getRepository('AppBundle:User')->findOneBy(['username' => $username]);
     if (!$user) {
         throw new \InvalidArgumentException(sprintf('Username %s is not known.', $username));
     }
     if ($input->getOption('admin')) {
         $group = $manager->getRepository('AppBundle:Group')->findOneBy(['code' => Group::SUPER_ADM]);
         if (!$group) {
             throw new \RuntimeException(sprintf('Group %s is not known.', Group::SUPER_ADM));
         }
         $user->setGroup($group);
     }
     $passwordService = $this->getContainer()->get('app.password');
     $password = $passwordService->generatePassword();
     $passwordService->changePassword($user, $password);
     $io->success('User edited');
     $io->text(sprintf('Username : %s', $username));
     $io->text(sprintf('Password: %s', $password));
     $io->text(sprintf('Group: %s (%s)', $user->getGroup()->getTitle(), $user->getGroup()->getCode()));
 }
Esempio n. 18
0
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $io = new SymfonyStyle($input, $output);
     $container = $this->aspectKernel->getContainer();
     $aspects = [];
     $io->title('Aspect debug information');
     $aspectName = $input->getOption('aspect');
     if (!$aspectName) {
         $io->text('<info>' . get_class($this->aspectKernel) . '</info> has following enabled aspects:');
         $aspects = $container->getByTag('aspect');
     } else {
         $aspect = $container->getAspect($aspectName);
         $aspects[] = $aspect;
     }
     $this->showRegisteredAspectsInfo($io, $aspects);
 }
Esempio n. 19
0
 /**
  * {@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());
         }
     }
 }
 private function recoverSpool($name, \Swift_Transport $transport, InputInterface $input, OutputInterface $output)
 {
     if ($transport instanceof \Swift_Transport_SpoolTransport) {
         $spool = $transport->getSpool();
         if ($spool instanceof \Swift_ConfigurableSpool) {
             $spool->setMessageLimit($input->getOption('message-limit'));
             $spool->setTimeLimit($input->getOption('time-limit'));
         }
         if ($spool instanceof \Swift_FileSpool) {
             if (null !== $input->getOption('recover-timeout')) {
                 $spool->recover($input->getOption('recover-timeout'));
             } else {
                 $spool->recover();
             }
         }
         $transportService = $input->getOption('transport') ?: sprintf('swiftmailer.mailer.%s.transport.real', $name);
         $sent = $spool->flushQueue($this->getContainer()->get($transportService));
         $this->io->text(sprintf('<comment>%d</comment> emails sent', $sent));
     }
 }
 private function normalizePeriods()
 {
     $this->io->newLine();
     $this->io->text('normalizing periods');
     $this->getContainer()->getParameter('locale');
     $this->io->progressStart();
     $periods = $this->em->getRepository('OjsJournalBundle:Period')->findAll();
     foreach ($periods as $period) {
         $getTranslation = $this->em->getRepository('OjsJournalBundle:PeriodTranslation')->findOneBy(['translatable' => $period, 'locale' => $this->locale]);
         if (!$getTranslation) {
             $this->io->progressAdvance();
             $newPeriodTranslation = new PeriodTranslation();
             $newPeriodTranslation->setTranslatable($period);
             $newPeriodTranslation->setLocale($this->locale);
             $newPeriodTranslation->setPeriod('-');
             $this->em->persist($newPeriodTranslation);
         }
     }
     $this->em->flush();
     $this->io->newLine();
 }
Esempio n. 22
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->io->title($this->getDescription());
     $this->io->text('Issue Total View Normalize Started');
     $this->normalizeIssueTotalArticleView();
     $this->io->text('Issue Total Download Normalize Started');
     $this->normalizeIssueTotalArticleDownload();
     $this->io->newLine();
     $this->io->text('Journal Normalize Started');
     $this->normalizeJournalTotalArticleView();
     $this->io->text('Journal Total View Normalize Finished');
     $this->normalizeJournalTotalArticleDownload();
     $this->io->text('Journal Total Download Normalize Finished');
     $this->io->newLine(2);
     $this->io->success('All process finished');
 }
 public function execute(SymfonyStyle $io = null)
 {
     $existingLocations = $this->em->getRepository('CampaignChainCoreBundle:Location')->findAll();
     if (empty($existingLocations)) {
         $io->text('There is no Location to update');
         return true;
     }
     $supportedLocationModuleIdentifiers = ['campaignchain-twitter-user' => $this->twitterUserMetrics, 'campaignchain-facebook-page' => $this->facebookPageMetrics];
     foreach ($existingLocations as $existingLocation) {
         if (!in_array($existingLocation->getLocationModule()->getIdentifier(), array_keys($supportedLocationModuleIdentifiers))) {
             continue;
         }
         //do we have already a scheduler?
         $existingScheduler = $this->em->getRepository('CampaignChainCoreBundle:SchedulerReportLocation')->findOneBy(['location' => $existingLocation]);
         if ($existingScheduler) {
             continue;
         }
         $service = $supportedLocationModuleIdentifiers[$existingLocation->getLocationModule()->getIdentifier()];
         $service->schedule($existingLocation);
     }
     $this->em->flush();
     return true;
 }
 /**
  * {@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');
 }
Esempio n. 25
0
 /**
  * Search for open jobs and executes them
  * then show a report about the done job.
  */
 protected function executeJobs()
 {
     // Get the Jobs to be processed.
     $jobsInQueue = $this->em->getRepository('CampaignChainCoreBundle:Job')->getOpenJobsForScheduler($this->scheduler);
     if (empty($jobsInQueue)) {
         return;
     }
     $this->io->section('Executing jobs now:');
     $this->logger->info('Executing {counter} jobs now:', ['counter' => count($jobsInQueue)]);
     $this->io->progressStart(count($jobsInQueue));
     foreach ($jobsInQueue as $jobInQueue) {
         // Execute job.
         $this->executeJob($jobInQueue);
         $this->io->progressAdvance();
     }
     // ensure that the progress bar is at 100%
     $this->io->progressFinish();
     $this->em->clear();
     // Get the processed jobs.
     $jobsProcessed = $this->em->getRepository('CampaignChainCoreBundle:Job')->getProcessedJobsForScheduler($this->scheduler);
     if (empty($jobsProcessed)) {
         return;
     }
     // Display the results of the execution.
     $tableHeader = ['Job ID', 'Operation ID', 'Process ID', 'Job Name', 'Job Start Date', 'Job End Date', 'Duration', 'Status', 'Message'];
     $outputTableRows = [];
     foreach ($jobsProcessed as $jobProcessed) {
         $startDate = null;
         $endDate = null;
         if ($jobProcessed->getStartDate()) {
             $startDate = $jobProcessed->getStartDate()->format('Y-m-d H:i:s');
         }
         if ($jobProcessed->getEndDate()) {
             $endDate = $jobProcessed->getEndDate()->format('Y-m-d H:i:s');
         }
         $jobData = [$jobProcessed->getId(), $jobProcessed->getActionId(), $jobProcessed->getPid(), $jobProcessed->getName(), $startDate, $endDate, $jobProcessed->getDuration() . ' ms', $jobProcessed->getStatus(), $jobProcessed->getMessage()];
         $outputTableRows[] = $jobData;
         if (Job::STATUS_ERROR === $jobProcessed->getStatus()) {
             $context = array_combine($tableHeader, $jobData);
             $this->logger->error($jobProcessed->getMessage(), $context);
         }
     }
     $this->io->text('Results of executed actions:');
     $this->io->table($tableHeader, $outputTableRows);
 }
Esempio n. 26
0
 public function text($message)
 {
     $message = sprintf('// %s', $message);
     parent::text($message);
 }
Esempio n. 27
0
 private function displayTxt(SymfonyStyle $io, array $filesInfo)
 {
     $countFiles = count($filesInfo);
     $erroredFiles = 0;
     foreach ($filesInfo as $info) {
         if ($info['valid'] && $this->displayCorrectFiles) {
             $io->comment('<info>OK</info>' . ($info['file'] ? sprintf(' in %s', $info['file']) : ''));
         } elseif (!$info['valid']) {
             ++$erroredFiles;
             $io->text('<error> ERROR </error>' . ($info['file'] ? sprintf(' in %s', $info['file']) : ''));
             $io->text(sprintf('<error> >> %s</error>', $info['message']));
         }
     }
     if ($erroredFiles === 0) {
         $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
     } else {
         $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
     }
     return min($erroredFiles, 1);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $targetArg = rtrim($input->getArgument('target'), '/');
     if (!is_dir($targetArg)) {
         throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target')));
     }
     $this->filesystem = $this->getContainer()->get('filesystem');
     // Create the bundles directory otherwise symlink will fail.
     $bundlesDir = $targetArg . '/bundles/';
     $this->filesystem->mkdir($bundlesDir, 0777);
     $io = new SymfonyStyle($input, $output);
     $io->newLine();
     if ($input->getOption('relative')) {
         $expectedMethod = self::METHOD_RELATIVE_SYMLINK;
         $io->text('Trying to install assets as <info>relative symbolic links</info>.');
     } elseif ($input->getOption('symlink')) {
         $expectedMethod = self::METHOD_ABSOLUTE_SYMLINK;
         $io->text('Trying to install assets as <info>absolute symbolic links</info>.');
     } else {
         $expectedMethod = self::METHOD_COPY;
         $io->text('Installing assets as <info>hard copies</info>.');
     }
     $io->newLine();
     $rows = array();
     $copyUsed = false;
     $exitCode = 0;
     /** @var BundleInterface $bundle */
     foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
         if (!is_dir($originDir = $bundle->getPath() . '/Resources/public')) {
             continue;
         }
         $targetDir = $bundlesDir . preg_replace('/bundle$/', '', strtolower($bundle->getName()));
         if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
             $message = sprintf("%s\n-> %s", $bundle->getName(), $targetDir);
         } else {
             $message = $bundle->getName();
         }
         try {
             $this->filesystem->remove($targetDir);
             if (self::METHOD_RELATIVE_SYMLINK === $expectedMethod) {
                 $method = $this->relativeSymlinkWithFallback($originDir, $targetDir);
             } elseif (self::METHOD_ABSOLUTE_SYMLINK === $expectedMethod) {
                 $method = $this->absoluteSymlinkWithFallback($originDir, $targetDir);
             } else {
                 $method = $this->hardCopy($originDir, $targetDir);
             }
             if (self::METHOD_COPY === $method) {
                 $copyUsed = true;
             }
             if ($method === $expectedMethod) {
                 $rows[] = array(sprintf('<fg=green;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'OK' : "✔"), $message, $method);
             } else {
                 $rows[] = array(sprintf('<fg=yellow;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'WARNING' : '!'), $message, $method);
             }
         } catch (\Exception $e) {
             $exitCode = 1;
             $rows[] = array(sprintf('<fg=red;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'ERROR' : "✘"), $message, $e->getMessage());
         }
     }
     $io->table(array('', 'Bundle', 'Method / Error'), $rows);
     if (0 !== $exitCode) {
         $io->error('Some errors occurred while installing assets.');
     } else {
         if ($copyUsed) {
             $io->note('Some assets were installed via copy. If you make changes to these assets you have to run this command again.');
         }
         $io->success('All assets were successfully installed.');
     }
     return $exitCode;
 }
Esempio n. 29
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'));
};
Esempio n. 30
0
 public function showLogo()
 {
     $this->io->text($this->logo);
 }