warning() public method

public warning ( $message )
Esempio n. 1
0
 /**
  * @inheritdoc
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $lockHandler = new LockHandler('app:sync.lock');
     if (!$lockHandler->lock()) {
         $io->warning('Sync process already running');
         return;
     }
     $service = $this->getContainer()->get('app.sync');
     switch ($input->getOption('type')) {
         case 'users':
             $service->syncUsers();
             break;
         case 'groups':
             $service->syncGroups();
             break;
         case 'grouphub':
             $service->syncGrouphubGroups();
             break;
         case 'queue':
             $service->syncGrouphubGroupsFromQueue();
             break;
         default:
             $service->sync();
     }
     $io->success('Done!');
 }
Esempio n. 2
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. 3
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->title('Payroll sending for ' . $input->getArgument('month'));
     try {
         $io->section('Checking server');
         $io->success($this->checkServer());
         $io->section('Processing Employee list');
         $this->bus->execute(new DistributePayroll(new PayrollMonth($input->getArgument('month'), $input->getArgument('year')), $input->getArgument('paths')));
         $io->success('Task ended.');
     } catch (\Milhojas\Infrastructure\Persistence\Management\Exceptions\PayrollRepositoryDoesNotExist $e) {
         $io->warning(array(sprintf($e->getMessage()), 'Please, review config/services/management.yml parameter: payroll.dataPath', 'Use a path to a valid folder containing payroll files or payroll zip archives.'));
     } catch (\Milhojas\Infrastructure\Persistence\Management\Exceptions\PayrollRepositoryForMonthDoesNotExist $e) {
         $io->warning(array($e->getMessage(), 'Please, add the needed folder or zip archives for month data.', 'Use a path to a valid folder containing payroll files.'));
     } catch (\RuntimeException $e) {
         $io->error(array($e->getMessage(), 'Check Internet connectivity and try again later.'));
     }
 }
 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);
     }
 }
 private function processMailer($name, InputInterface $input, OutputInterface $output)
 {
     if (!$this->getContainer()->has(sprintf('swiftmailer.mailer.%s', $name))) {
         throw new \InvalidArgumentException(sprintf('The mailer "%s" does not exist.', $name));
     }
     $this->io->text(sprintf('<info>[%s]</info> Processing <info>%s</info> mailer spool... ', date('Y-m-d H:i:s'), $name));
     if ($this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name))) {
         $mailer = $this->getContainer()->get(sprintf('swiftmailer.mailer.%s', $name));
         $transport = $mailer->getTransport();
         if ($transport instanceof \Swift_Transport_LoadBalancedTransport) {
             foreach ($transport->getTransports() as $eachTransport) {
                 $this->recoverSpool($name, $eachTransport, $input, $output);
             }
         } else {
             $this->recoverSpool($name, $transport, $input, $output);
         }
     } else {
         $this->io->warning('There are no emails to send because the spool is disabled.');
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $name = $input->getArgument('name');
     $timeWindowService = $this->getContainer()->get('mablae_time_window.service');
     $result = $timeWindowService->isTimeWindowActive($name);
     $io = new SymfonyStyle($input, $output);
     if ($result == true) {
         $io->success("The time window '{$name}' is active!");
     } else {
         $io->warning("The time window '{$name}' is NOT active!");
     }
 }
Esempio n. 7
0
 /**
  * Check single backup-configuration.
  *
  * @param PluginRegistry $plugins
  * @param SymfonyStyle $io
  * @param string $name
  * @param array $backup
  *
  * @return bool
  */
 private function checkBackup(PluginRegistry $plugins, SymfonyStyle $io, $name, array $backup)
 {
     $io->section('Backup: ' . $name);
     if (!$plugins->has($backup['plugin'])) {
         $io->warning(sprintf('Plugin "%s" not found', $backup['plugin']));
         return false;
     }
     $optionsResolver = new OptionsResolver();
     $plugins->getPlugin($backup['plugin'])->configureOptionsResolver($optionsResolver);
     try {
         $parameter = $optionsResolver->resolve($backup['parameter']);
     } catch (InvalidArgumentException $e) {
         $io->warning(sprintf('Parameter not valid' . PHP_EOL . PHP_EOL . 'Message: "%s"', $e->getMessage()));
         return false;
     }
     $io->write('Parameter:');
     $messages = array_filter(explode("\r\n", Yaml::dump($parameter)));
     $io->block($messages, null, null, '  ');
     $io->writeln('OK');
     return true;
 }
 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);
     $address = $input->getArgument('address');
     // remove an orphaned lock file
     if (file_exists($this->getLockFile($address)) && !$this->isServerRunning($address)) {
         unlink($this->getLockFile($address));
     }
     if (file_exists($this->getLockFile($address))) {
         $io->success(sprintf('MongoDB server still listening on mongodb://%s', $address));
     } else {
         $io->warning(sprintf('No server is listening on mongodb://%s', $address));
     }
 }
Esempio n. 10
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     /** @var FileLoader $fixtureService */
     $fixtureService = $this->getContainer()->get('campaignchain.core.fixture');
     if ($fixtureService->load($input->getArgument('files'), $input->getOption('doDrop'))) {
         // Load schema updates.
         $this->loadSchemaUpdateVersions($input, $output);
         $io->success('Successfully loaded fixture files.');
     } elseif ($fixtureService->getException()) {
         $io->warning($fixtureService->getException()->getMessage());
     }
     return;
 }
Esempio n. 11
0
    /**
     * Executes the command thumbnail:delete.
     *
     * Deletes all existing thumbnails and updates the database accordingly.
     *
     * @param InputInterface $input The input stream used to get the argument and verbose option.
     * @param OutputInterface $output The output stream, used for printing verbose-mode and error information.
     *
     * @return int 0 if all is ok, 1 if a thumbnail couldn't be deleted.
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->section($this->user->lang('CLI_THUMBNAIL_DELETING'));
        $sql = 'SELECT COUNT(*) AS nb_missing_thumbnails
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE thumbnail = 1';
        $result = $this->db->sql_query($sql);
        $nb_missing_thumbnails = (int) $this->db->sql_fetchfield('nb_missing_thumbnails');
        $this->db->sql_freeresult($result);
        if ($nb_missing_thumbnails === 0) {
            $io->warning($this->user->lang('CLI_THUMBNAIL_NOTHING_TO_DELETE'));
            return 0;
        }
        $sql = 'SELECT attach_id, physical_filename, extension, real_filename, mimetype
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE thumbnail = 1';
        $result = $this->db->sql_query($sql);
        $progress = $this->create_progress_bar($nb_missing_thumbnails, $io, $output);
        $progress->setMessage($this->user->lang('CLI_THUMBNAIL_DELETING'));
        $progress->start();
        $thumbnail_deleted = array();
        $return = 0;
        while ($row = $this->db->sql_fetchrow($result)) {
            $thumbnail_path = $this->phpbb_root_path . 'files/thumb_' . $row['physical_filename'];
            if (@unlink($thumbnail_path)) {
                $thumbnail_deleted[] = $row['attach_id'];
                if (sizeof($thumbnail_deleted) === 250) {
                    $this->commit_changes($thumbnail_deleted);
                    $thumbnail_deleted = array();
                }
                $progress->setMessage($this->user->lang('CLI_THUMBNAIL_DELETED', $row['real_filename'], $row['physical_filename']));
            } else {
                $return = 1;
                $progress->setMessage('<error>' . $this->user->lang('CLI_THUMBNAIL_SKIPPED', $row['real_filename'], $row['physical_filename']) . '</error>');
            }
            $progress->advance();
        }
        $this->db->sql_freeresult($result);
        if (!empty($thumbnail_deleted)) {
            $this->commit_changes($thumbnail_deleted);
        }
        $progress->finish();
        $io->newLine(2);
        $io->success($this->user->lang('CLI_THUMBNAIL_DELETING_DONE'));
        return $return;
    }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = $address . ':' . $input->getOption('port');
     }
     // remove an orphaned lock file
     if (file_exists($this->getLockFile($address)) && !$this->isServerRunning($address)) {
         unlink($this->getLockFile($address));
     }
     if (file_exists($this->getLockFile($address))) {
         $io->success(sprintf('Web server still listening on http://%s', $address));
     } else {
         $io->warning(sprintf('No web server is listening on http://%s', $address));
     }
 }
Esempio n. 13
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $dbPath = $input->getOption('dbpath');
     $fs = new Filesystem();
     try {
         $fs->mkdir('data/mongodb/');
     } catch (IOException $e) {
         $io->warning('Could not create "data/mongodb/" directory');
     }
     // $env = $this->getContainer()->getParameter('kernel.environment');
     $env = null;
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = $address . ':' . $input->getOption('port');
     }
     if ($this->isOtherServerProcessRunning($address)) {
         $io->error(sprintf('A process is already listening on mongodb://%s.', $address));
         return 1;
     }
     /*
     if ('prod' === $env) {
         $io->error('Running PHP built-in server in production environment is NOT recommended!');
     }
     */
     $io->success(sprintf('Server running on mongodb://%s', $address));
     $io->comment('Quit the server with CONTROL-C.');
     if (null === ($builder = $this->createProcessBuilder($io, $input->getArgument('address'), $input->getOption('port'), $dbPath))) {
         return 1;
     }
     //$builder->setWorkingDirectory($documentRoot);
     $builder->setTimeout(null);
     $process = $builder->getProcess();
     if (OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) {
         $process->disableOutput();
     }
     $this->getHelper('process')->run($output, $process, null, null, OutputInterface::VERBOSITY_VERBOSE);
     if (!$process->isSuccessful()) {
         $errorMessages = array('Built-in server terminated unexpectedly.');
         if ($process->isOutputDisabled()) {
             $errorMessages[] = 'Run the command again with -v option for more details.';
         }
         $io->error($errorMessages);
     }
     return $process->getExitCode();
 }
 /**
  * {@inheritdoc}
  *
  * @throws \LogicException
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $dispatcher = $this->getEventDispatcher();
     $options = array();
     if ($event = $input->getArgument('event')) {
         if (!$dispatcher->hasListeners($event)) {
             $io->warning(sprintf('The event "%s" does not have any registered listeners.', $event));
             return;
         }
         $options = array('event' => $event);
     }
     $helper = new DescriptorHelper();
     $options['format'] = $input->getOption('format');
     $options['raw_text'] = $input->getOption('raw');
     $options['output'] = $io;
     $helper->describe($io, $dispatcher, $options);
 }
Esempio n. 15
0
 /**
  * @param array    $symbol
  * @param DateTime $lastSunday
  *
  * @throws Exception
  */
 public function writeSymbol($symbol, DateTime $lastSunday)
 {
     $dates = $this->getDatesFromSymbol($symbol, $lastSunday);
     foreach ($dates as $date) {
         for ($i = 0; $i < $date['count']; $i++) {
             $this->addCommit($date['date']);
             echo '.';
         }
     }
     echo "\n";
     if ($this->force) {
         $this->forcePush();
         $this->io->comment('Git local checkout has been created and pushed to the origin repository. You can now view it online.');
     } else {
         $this->io->warning('Git local checkout has been created but not sent. Use --force to really push it to the github account.');
     }
     $this->io->success('Done.');
 }
Esempio n. 16
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $fs = new Filesystem();
     try {
         $fs->remove('data/mongodb/');
     } catch (IOException $e) {
         $io->warning('Could not remove "data/mongodb/" directory');
     }
     $this->runSubCommand('model:create', $output, ['model' => 'Hive\\Demo\\Model\\User', 'fields' => ['email:string:email', 'name:string:name', 'url:string:url', 'posts:references[Hive\\Demo\\Model\\Post,user]']]);
     $this->runSubCommand('model:create', $output, ['model' => 'Hive\\Demo\\Model\\Post', 'fields' => ['title:string:sentence', 'body:string:text', 'user:reference[Hive\\Demo\\Model\\User,posts]:reference']]);
     $this->runSubCommand('scaffold:api', $output, ['models' => ['Hive\\Demo\\Model\\User', 'Hive\\Demo\\Model\\Post']]);
     $this->runSubCommand('scaffold:ui', $output, ['models' => ['Hive\\Demo\\Model\\User', 'Hive\\Demo\\Model\\Post']]);
     $this->runSubCommand('server:start', $output);
     $this->runSubCommand('mongodb:start', $output);
     if ($input->getOption('seed')) {
         $this->runSubCommand('model:seed', $output, ['model' => 'Hive\\Demo\\Model\\User', 'seeds' => 500]);
         $this->runSubCommand('model:seed', $output, ['model' => 'Hive\\Demo\\Model\\Post', 'seeds' => 10000]);
     }
     $io->success(['Hive created on http://localhost:8000/api/v1/', 'Login with your email and password: "******"']);
 }
 protected function execute(Input\InputInterface $input, Output\OutputInterface $output)
 {
     $this->stopwatch->start('changelog');
     $io = new SymfonyStyle($input, $output);
     $io->title('Localheinz GitHub Changelog');
     $authToken = $input->getOption('auth-token');
     if (null !== $authToken) {
         $this->client->authenticate($authToken, Client::AUTH_HTTP_TOKEN);
     }
     $owner = $input->getArgument('owner');
     $repository = $input->getArgument('repository');
     $startReference = $input->getArgument('start-reference');
     $endReference = $input->getArgument('end-reference');
     $range = $this->range($startReference, $endReference);
     $io->section(sprintf('Pull Requests for %s/%s %s', $owner, $repository, $range));
     try {
         $range = $this->pullRequestRepository->items($owner, $repository, $startReference, $endReference);
     } catch (\Exception $exception) {
         $io->error(sprintf('An error occurred: %s', $exception->getMessage()));
         return 1;
     }
     $pullRequests = $range->pullRequests();
     if (!count($pullRequests)) {
         $io->warning('Could not find any pull requests');
     } else {
         $template = $input->getOption('template');
         $pullRequests = array_reverse($pullRequests);
         array_walk($pullRequests, function (Resource\PullRequestInterface $pullRequest) use($output, $template) {
             $message = str_replace(['%title%', '%id%'], [$pullRequest->title(), $pullRequest->id()], $template);
             $output->writeln($message);
         });
         $io->newLine();
         $io->success(sprintf('Found %s pull request%s.', count($pullRequests), count($pullRequests) === 1 ? '' : 's', $range));
     }
     $event = $this->stopwatch->stop('changelog');
     $io->writeln($this->formatStopwatchEvent($event));
     return 0;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $locale = $input->getArgument('locale');
     $domain = $input->getOption('domain');
     /** @var TranslationLoader $loader */
     $loader = $this->getContainer()->get('translation.loader');
     /** @var Kernel $kernel */
     $kernel = $this->getContainer()->get('kernel');
     // Define Root Path to App folder
     $transPaths = array($kernel->getRootDir() . '/Resources/');
     // Override with provided Bundle info
     if (null !== $input->getArgument('bundle')) {
         try {
             $bundle = $kernel->getBundle($input->getArgument('bundle'));
             $transPaths = array($bundle->getPath() . '/Resources/', sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName()));
         } catch (\InvalidArgumentException $e) {
             // such a bundle does not exist, so treat the argument as path
             $transPaths = array($input->getArgument('bundle') . '/Resources/');
             if (!is_dir($transPaths[0])) {
                 throw new \InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0]));
             }
         }
     } elseif ($input->getOption('all')) {
         foreach ($kernel->getBundles() as $bundle) {
             $transPaths[] = $bundle->getPath() . '/Resources/';
             $transPaths[] = sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName());
         }
     }
     // Extract used messages
     $extractedCatalogue = $this->extractMessages($locale, $transPaths);
     // Load defined messages
     $currentCatalogue = $this->loadCurrentMessages($locale, $transPaths, $loader);
     // Merge defined and extracted messages to get all message ids
     $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue);
     $allMessages = $mergeOperation->getResult()->all($domain);
     if (null !== $domain) {
         $allMessages = array($domain => $allMessages);
     }
     // No defined or extracted messages
     if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) {
         $outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale);
         if (null !== $domain) {
             $outputMessage .= sprintf(' and domain "%s"', $domain);
         }
         $io->warning($outputMessage);
         return;
     }
     // Load the fallback catalogues
     $fallbackCatalogues = $this->loadFallbackCatalogues($locale, $transPaths, $loader);
     // Display header line
     $headers = array('State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale));
     foreach ($fallbackCatalogues as $fallbackCatalogue) {
         $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale());
     }
     $rows = array();
     // Iterate all message ids and determine their state
     foreach ($allMessages as $domain => $messages) {
         foreach (array_keys($messages) as $messageId) {
             $value = $currentCatalogue->get($messageId, $domain);
             $states = array();
             if ($extractedCatalogue->defines($messageId, $domain)) {
                 if (!$currentCatalogue->defines($messageId, $domain)) {
                     $states[] = self::MESSAGE_MISSING;
                 }
             } elseif ($currentCatalogue->defines($messageId, $domain)) {
                 $states[] = self::MESSAGE_UNUSED;
             }
             if (!in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused') || !in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) {
                 continue;
             }
             foreach ($fallbackCatalogues as $fallbackCatalogue) {
                 if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) {
                     $states[] = self::MESSAGE_EQUALS_FALLBACK;
                     break;
                 }
             }
             $row = array($this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value));
             foreach ($fallbackCatalogues as $fallbackCatalogue) {
                 $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain));
             }
             $rows[] = $row;
         }
     }
     $io->table($headers, $rows);
 }
Esempio n. 19
0
<?php

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
//Ensure has single blank line between titles and blocks
return function (InputInterface $input, OutputInterface $output) {
    $output = new SymfonyStyle($input, $output);
    $output->title('Title');
    $output->warning('Lorem ipsum dolor sit amet');
    $output->title('Title');
};
Esempio n. 20
0
 /**
  * @param string $msg
  */
 protected function warning($msg)
 {
     if ($this->io) {
         $this->io->warning(date('[Y-m-d H:i:s]') . $msg);
     }
 }
Esempio n. 21
0
    /**
     * Executes the command thumbnail:generate.
     *
     * Generate a thumbnail for all attachments which need one and don't have it yet.
     *
     * @param InputInterface $input The input stream used to get the argument and verboe option.
     * @param OutputInterface $output The output stream, used for printing verbose-mode and error information.
     *
     * @return int 0.
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->section($this->user->lang('CLI_THUMBNAIL_GENERATING'));
        $sql = 'SELECT COUNT(*) AS nb_missing_thumbnails
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE thumbnail = 0';
        $result = $this->db->sql_query($sql);
        $nb_missing_thumbnails = (int) $this->db->sql_fetchfield('nb_missing_thumbnails');
        $this->db->sql_freeresult($result);
        if ($nb_missing_thumbnails === 0) {
            $io->warning($this->user->lang('CLI_THUMBNAIL_NOTHING_TO_GENERATE'));
            return 0;
        }
        $extensions = $this->cache->obtain_attach_extensions(true);
        $sql = 'SELECT attach_id, physical_filename, extension, real_filename, mimetype
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE thumbnail = 0';
        $result = $this->db->sql_query($sql);
        if (!function_exists('create_thumbnail')) {
            require $this->phpbb_root_path . 'includes/functions_posting.' . $this->php_ext;
        }
        $progress = $this->create_progress_bar($nb_missing_thumbnails, $io, $output);
        $progress->setMessage($this->user->lang('CLI_THUMBNAIL_GENERATING'));
        $progress->start();
        $thumbnail_created = array();
        while ($row = $this->db->sql_fetchrow($result)) {
            if (isset($extensions[$row['extension']]['display_cat']) && $extensions[$row['extension']]['display_cat'] == ATTACHMENT_CATEGORY_IMAGE) {
                $source = $this->phpbb_root_path . 'files/' . $row['physical_filename'];
                $destination = $this->phpbb_root_path . 'files/thumb_' . $row['physical_filename'];
                if (create_thumbnail($source, $destination, $row['mimetype'])) {
                    $thumbnail_created[] = (int) $row['attach_id'];
                    if (count($thumbnail_created) === 250) {
                        $this->commit_changes($thumbnail_created);
                        $thumbnail_created = array();
                    }
                    $progress->setMessage($this->user->lang('CLI_THUMBNAIL_GENERATED', $row['real_filename'], $row['physical_filename']));
                } else {
                    $progress->setMessage('<info>' . $this->user->lang('CLI_THUMBNAIL_SKIPPED', $row['real_filename'], $row['physical_filename']) . '</info>');
                }
            }
            $progress->advance();
        }
        $this->db->sql_freeresult($result);
        if (!empty($thumbnail_created)) {
            $this->commit_changes($thumbnail_created);
        }
        $progress->finish();
        $io->newLine(2);
        $io->success($this->user->lang('CLI_THUMBNAIL_GENERATING_DONE'));
        return 0;
    }
Esempio n. 22
0
<?php

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
//Ensure has single blank line between blocks
return function (InputInterface $input, OutputInterface $output) {
    $output = new SymfonyStyle($input, $output);
    $output->warning('Warning');
    $output->caution('Caution');
    $output->error('Error');
    $output->success('Success');
    $output->note('Note');
    $output->block('Custom block', 'CUSTOM', 'fg=white;bg=green', 'X ', true);
};
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output = new SymfonyStyle($input, $output);
     if (false !== strpos($input->getFirstArgument(), ':d')) {
         $output->caution('The use of "translation:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:translation" instead.');
     }
     $locale = $input->getArgument('locale');
     $domain = $input->getOption('domain');
     $loader = $this->getContainer()->get('translation.loader');
     $kernel = $this->getContainer()->get('kernel');
     // Define Root Path to App folder
     $rootPath = $kernel->getRootDir();
     // Override with provided Bundle info
     if (null !== $input->getArgument('bundle')) {
         try {
             $rootPath = $kernel->getBundle($input->getArgument('bundle'))->getPath();
         } catch (\InvalidArgumentException $e) {
             // such a bundle does not exist, so treat the argument as path
             $rootPath = $input->getArgument('bundle');
             if (!is_dir($rootPath)) {
                 throw new \InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $rootPath));
             }
         }
     }
     // get bundle directory
     $translationsPath = $rootPath . '/Resources/translations';
     // Extract used messages
     $extractedCatalogue = new MessageCatalogue($locale);
     if (is_dir($rootPath . '/Resources/views')) {
         $this->getContainer()->get('translation.extractor')->extract($rootPath . '/Resources/views', $extractedCatalogue);
     }
     // Load defined messages
     $currentCatalogue = new MessageCatalogue($locale);
     if (is_dir($translationsPath)) {
         $loader->loadMessages($translationsPath, $currentCatalogue);
     }
     // Merge defined and extracted messages to get all message ids
     $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue);
     $allMessages = $mergeOperation->getResult()->all($domain);
     if (null !== $domain) {
         $allMessages = array($domain => $allMessages);
     }
     // No defined or extracted messages
     if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) {
         $outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale);
         if (null !== $domain) {
             $outputMessage .= sprintf(' and domain "%s"', $domain);
         }
         $output->warning($outputMessage);
         return;
     }
     // Load the fallback catalogues
     $fallbackCatalogues = array();
     $translator = $this->getContainer()->get('translator');
     if ($translator instanceof Translator) {
         foreach ($translator->getFallbackLocales() as $fallbackLocale) {
             if ($fallbackLocale === $locale) {
                 continue;
             }
             $fallbackCatalogue = new MessageCatalogue($fallbackLocale);
             $loader->loadMessages($translationsPath, $fallbackCatalogue);
             $fallbackCatalogues[] = $fallbackCatalogue;
         }
     }
     // Display header line
     $headers = array('State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale));
     foreach ($fallbackCatalogues as $fallbackCatalogue) {
         $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale());
     }
     $rows = array();
     // Iterate all message ids and determine their state
     foreach ($allMessages as $domain => $messages) {
         foreach (array_keys($messages) as $messageId) {
             $value = $currentCatalogue->get($messageId, $domain);
             $states = array();
             if ($extractedCatalogue->defines($messageId, $domain)) {
                 if (!$currentCatalogue->defines($messageId, $domain)) {
                     $states[] = self::MESSAGE_MISSING;
                 }
             } elseif ($currentCatalogue->defines($messageId, $domain)) {
                 $states[] = self::MESSAGE_UNUSED;
             }
             if (!in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused') || !in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) {
                 continue;
             }
             foreach ($fallbackCatalogues as $fallbackCatalogue) {
                 if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) {
                     $states[] = self::MESSAGE_EQUALS_FALLBACK;
                     break;
                 }
             }
             $row = array($this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value));
             foreach ($fallbackCatalogues as $fallbackCatalogue) {
                 $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain));
             }
             $rows[] = $row;
         }
     }
     $output->table($headers, $rows);
 }
Esempio n. 24
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     if (!extension_loaded('pcntl')) {
         $io->error(array('This command needs the pcntl extension to run.', 'You can either install it or use the "mongodb:run" command instead to run the MongoDB server.'));
         if ($io->ask('Do you want to execute <info>mongodb:run</info> immediately? [Yn] ', true)) {
             $command = $this->getApplication()->find('mongodb:run');
             return $command->run($input, $output);
         }
         return 1;
     }
     $dbPath = $input->getOption('dbpath');
     $fs = new Filesystem();
     try {
         $fs->mkdir('data/mongodb/');
     } catch (IOException $e) {
         $io->warning('Could not create "data/mongodb/" directory');
     }
     // $env = $this->getContainer()->getParameter('kernel.environment');
     $env = null;
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = $address . ':' . $input->getOption('port');
     }
     if (!$input->getOption('force') && $this->isOtherServerProcessRunning($address)) {
         $io->error(array(sprintf('A process is already listening on mongodb://%s.', $address), 'Use the --force option if the server process terminated unexpectedly to start a new MongoDB server process.'));
         return 1;
     }
     $pid = pcntl_fork();
     if ($pid < 0) {
         $io->error('Unable to start the server process.');
         return 1;
     }
     if ($pid > 0) {
         $io->success(sprintf('MongoDB server listening on mongodb://%s', $address));
         return;
     }
     if (posix_setsid() < 0) {
         $io->error('Unable to set the child process as session leader');
         return 1;
     }
     if (null === ($process = $this->createServerProcess($io, $input->getArgument('address'), $input->getOption('port'), $dbPath))) {
         return 1;
     }
     $process->disableOutput();
     $process->start();
     $lockFile = $this->getLockFile($address);
     touch($lockFile);
     if (!$process->isRunning()) {
         $io->error('Unable to start the server process');
         unlink($lockFile);
         return 1;
     }
     // stop the web server when the lock file is removed
     while ($process->isRunning()) {
         if (!file_exists($lockFile)) {
             $process->stop();
         }
         sleep(1);
     }
 }
Esempio n. 25
0
 /**
  * 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;
 }
 /**
  * Exceptional occurrences that are not errors.
  *
  * Example: Use of deprecated APIs, poor use of an API, undesirable things
  * that are not necessarily wrong.
  *
  * @param string $message
  * @param array $context
  * @return null
  */
 public function warning($message, array $context = array())
 {
     $this->outputStyle->warning($message);
 }
Esempio n. 27
0
 private function displayTxt(OutputInterface $output, SymfonyStyle $io, $filesInfo)
 {
     $errors = 0;
     foreach ($filesInfo as $info) {
         if ($info['valid'] && $output->isVerbose()) {
             $io->comment('<info>OK</info>' . ($info['file'] ? sprintf(' in %s', $info['file']) : ''));
         } elseif (!$info['valid']) {
             ++$errors;
             $io->text(sprintf('<error> ERROR </error> in %s', $info['file']));
             $io->text(sprintf('<error> >> %s</error>', $info['message']));
         }
     }
     if ($errors === 0) {
         $io->success(sprintf('All %d YAML files contain valid syntax.', count($filesInfo)));
     } else {
         $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', count($filesInfo) - $errors, $errors));
     }
     return min($errors, 1);
 }
Esempio n. 28
0
    /**
     * Executes the command thumbnail:generate.
     *
     * Generate a thumbnail for all attachments which need one and don't have it yet.
     *
     * @param InputInterface $input The input stream used to get the argument and verboe option.
     * @param OutputInterface $output The output stream, used for printing verbose-mode and error information.
     *
     * @return int 0.
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->section($this->user->lang('CLI_THUMBNAIL_GENERATING'));
        $sql = 'SELECT COUNT(*) AS nb_missing_thumbnails
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE thumbnail = 0';
        $result = $this->db->sql_query($sql);
        $nb_missing_thumbnails = (int) $this->db->sql_fetchfield('nb_missing_thumbnails');
        $this->db->sql_freeresult($result);
        if ($nb_missing_thumbnails === 0) {
            $io->warning($this->user->lang('CLI_THUMBNAIL_NOTHING_TO_GENERATE'));
            return 0;
        }
        $extensions = $this->cache->obtain_attach_extensions(true);
        $sql = 'SELECT attach_id, physical_filename, extension, real_filename, mimetype
			FROM ' . ATTACHMENTS_TABLE . '
			WHERE thumbnail = 0';
        $result = $this->db->sql_query($sql);
        if (!function_exists('create_thumbnail')) {
            require $this->phpbb_root_path . 'includes/functions_posting.' . $this->php_ext;
        }
        $progress = $io->createProgressBar($nb_missing_thumbnails);
        if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) {
            $progress->setFormat('<info>[%percent:3s%%]</info> %message%');
            $progress->setOverwrite(false);
        } else {
            if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
                $progress->setFormat('<info>[%current:s%/%max:s%]</info><comment>[%elapsed%/%estimated%][%memory%]</comment> %message%');
                $progress->setOverwrite(false);
            } else {
                $io->newLine(2);
                $progress->setFormat("    %current:s%/%max:s% %bar%  %percent:3s%%\n" . "                         %elapsed:6s%/%estimated:-6s% %memory:6s%\n");
                $progress->setBarWidth(60);
            }
        }
        if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
            $progress->setEmptyBarCharacter('░');
            // light shade character \u2591
            $progress->setProgressCharacter('');
            $progress->setBarCharacter('▓');
            // dark shade character \u2593
        }
        $progress->setMessage($this->user->lang('CLI_THUMBNAIL_GENERATING'));
        $progress->start();
        $thumbnail_created = array();
        while ($row = $this->db->sql_fetchrow($result)) {
            if (isset($extensions[$row['extension']]['display_cat']) && $extensions[$row['extension']]['display_cat'] == ATTACHMENT_CATEGORY_IMAGE) {
                $source = $this->phpbb_root_path . 'files/' . $row['physical_filename'];
                $destination = $this->phpbb_root_path . 'files/thumb_' . $row['physical_filename'];
                if (create_thumbnail($source, $destination, $row['mimetype'])) {
                    $thumbnail_created[] = (int) $row['attach_id'];
                    if (count($thumbnail_created) === 250) {
                        $this->commit_changes($thumbnail_created);
                        $thumbnail_created = array();
                    }
                    $progress->setMessage($this->user->lang('CLI_THUMBNAIL_GENERATED', $row['real_filename'], $row['physical_filename']));
                } else {
                    $progress->setMessage('<info>' . $this->user->lang('CLI_THUMBNAIL_SKIPPED', $row['real_filename'], $row['physical_filename']) . '</info>');
                }
            }
            $progress->advance();
        }
        $this->db->sql_freeresult($result);
        if (!empty($thumbnail_created)) {
            $this->commit_changes($thumbnail_created);
        }
        $progress->finish();
        $io->newLine(2);
        $io->success($this->user->lang('CLI_THUMBNAIL_GENERATING_DONE'));
        return 0;
    }
 /**
  * {@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. 30
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);
 }