setMessage() public method

The text is displayed when the progress bar is rendered but only when the corresponding placeholder is part of the custom format line (by wrapping the name with %).
public setMessage ( string $message, string $name = 'message' )
$message string The text to associate with the placeholder
$name string The name of the placeholder
 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));
 }
Beispiel #2
0
 /**
  * Set progress bar. Once a progress bar has been set on an invoker, it
  * cannot be undone. Instantiate a new invoker if needed. Sub sequent calls
  * to `Invoker::execute()` will reuse the progress bar object.
  *
  * @param ProgressBar $bar
  * @return Invoker
  */
 public function setProgressBar(ProgressBar $bar)
 {
     // start progress bar
     $this->dispatcher->addListener(Events::INVOKER_START, function (InvokerEvent $event) use($bar) {
         $bar->start($event->getSteps()->getUnits());
     });
     // finish progress bar
     $this->dispatcher->addListener(Events::INVOKER_FINISH, function (InvokerEvent $event) use($bar) {
         $bar->setMessage('Finished: ' . $event->getSteps()->getName());
         $bar->finish();
     });
     // step start
     $this->dispatcher->addListener(Events::STEP_BEFORE_EXECUTE, function (StepEvent $event) use($bar) {
         $bar->setMessage($event->getStep()->getDescription() . '...');
         $bar->display();
     });
     // step finish
     $this->dispatcher->addListener(Events::STEP_AFTER_EXECUTE, function (StepEvent $event) use($bar) {
         $bar->advance($event->getStep()->getTicksRemaining());
     });
     // step tick
     $this->dispatcher->addListener(Events::STEP_TICK, function (StepEvent $event) use($bar) {
         $bar->advance($event->getStep()->getTick());
     });
     return $this;
 }
 /**
  * @param OutputInterface $output
  * @param Repository $source
  * @param WritableRepository $destination
  */
 private function setupProgressBar(OutputInterface $output, Repository $source, WritableRepository $destination)
 {
     $this->progress = new ProgressBar($output, count($source));
     $this->progress->setMessage('Generating database...');
     $this->progress->start();
     $destination->attach($this);
 }
 /**
  * @param $total
  * @param OutputInterface $output
  * @param callable        $callback
  */
 public function mainProgressBarAction($total, $output, callable $callback)
 {
     // Перенос строки
     $output->writeln("\n");
     // Инициализируем прогресс бар
     $progress = new ProgressBar($output, $total);
     $progress->setFormat("<info>%message%\n Фильм %current% из %max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%</info>");
     $progress->setMessage('Процесс запущен');
     $progress->start();
     // Инициализируем цикл и выполняем
     $progress->setMessage('В процессе...');
     for ($i = 0; $i < $total; $i++) {
         // Задержка
         sleep(Config::DELAY_BETWEEN_REQUESTS);
         // Выполняем колбэк
         $callback();
         // Передвигаем прогресс бар
         $progress->advance();
     }
     // Завершаем прогресс бар
     $progress->setMessage('Процесс завершен');
     $progress->finish();
     // Перенос строки
     $output->writeln("\n");
 }
Beispiel #5
0
 /**
  * @param TaskEvent $event
  */
 public function advanceProgress(TaskEvent $event)
 {
     $taskReflection = new ReflectionClass($event->getTask());
     $taskName = $taskReflection->getShortName();
     $this->progressBar->setFormat($this->progressFormat);
     $this->progressBar->setMessage($taskName);
     $this->progressBar->advance();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $config = $this->get('config');
     $client = $this->get('client');
     $type = $input->getOption('type');
     if (empty($type)) {
         $type = $config->get('default_type');
     }
     $filter = sprintf('%s is null', self::UNSUBSCRIBE_ATTRIBUTE);
     if (!empty($input->getArgument('filter'))) {
         $filter .= ' AND (' . $input->getArgument('filter') . ')';
     }
     // Total count records with unsubscribe attribute value empty / null.
     $total_count = $this->getEntityCount($type, $filter);
     $output->writeln(sprintf('<info>Found %d records where "%s"</info>', $total_count, $filter));
     // Confirm update.
     $question = new ConfirmationQuestion(sprintf('Update these %d records? [y/n] ', $total_count), false);
     $helper = $this->getHelper('question');
     if (!$helper->ask($input, $output, $question)) {
         exit(0);
     }
     $progress = new ProgressBar($output, $total_count);
     $progress->setFormat(" %current%/%max% [%bar%] %percent:3s%% \n%message%");
     $updateParams = array('type_name' => $type, 'attributes' => array(self::UNSUBSCRIBE_ATTRIBUTE => ''));
     $succeed = 0;
     $failed = 0;
     $offset = 0;
     $records = $this->retrieveRecords($this->getQueryParams($offset, $type, $filter));
     if (empty($records)) {
         $output->write('No records to update.');
         exit(0);
     }
     $progress->setMessage('Retrieving records...');
     $progress->start();
     while (!empty($records)) {
         foreach ($records as $record) {
             $updateParams['attributes'][self::UNSUBSCRIBE_ATTRIBUTE] = sha1($record['uuid'] . $record['created']);
             $progress->setMessage(sprintf('Update record with id %s', $record['id']));
             $result = $client->api('entity')->updateById($record['id'], $updateParams);
             if ('ok' === strtolower($result['stat'])) {
                 $succeed++;
             } else {
                 $failed++;
             }
             $progress->advance();
         }
         $offset += sizeof($records);
         $progress->setMessage('Retrieving records...');
         $records = $this->retrieveRecords($this->getQueryParams($offset, $type, $filter));
     }
     if ($failed > 0) {
         $progress->setMessage(sprintf('<info>%d</info> records are successfully updated, but<error>%d</error> records are failed to update. Please try run this command again.', $succeed, $failed));
     } else {
         $progress->setMessage(sprintf('<info>%d</info> records are successfully updated.', $succeed));
     }
     $progress->finish();
     exit($failed > 0 ? 1 : 0);
 }
Beispiel #7
0
 /**
  * @param RunnerEvent $runnerEvent
  */
 public function finishProgress(RunnerEvent $runnerEvent)
 {
     if ($this->progressBar->getProgress() != $this->progressBar->getMaxSteps()) {
         $this->progressBar->setFormat('<fg=red>%message%</fg=red>');
         $this->progressBar->setMessage('Aborted ...');
     }
     $this->progressBar->finish();
     $this->output->writeln('');
 }
Beispiel #8
0
 /**
  * Log
  *
  * @param string $message
  */
 public function log($message)
 {
     if ($this->progress) {
         $this->progress->setMessage($message);
         $this->logs[] = $message;
     } else {
         $this->output->writeLn($message);
     }
 }
Beispiel #9
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)
 {
     $entity = $input->getArgument('entity');
     /** @var EntityManager $entityManager */
     $entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
     if ($entity === 'article') {
         $output->writeln('<comment>This might take a while.</comment>');
         $journals = $entityManager->getRepository('OjsJournalBundle:Journal')->findAll();
         $totalProgress = new ProgressBar($output, count($journals));
         $totalProgress->setFormat('%current%/%max% [%bar%] %message%');
         if ($totalProgress->getMaxSteps() > 0) {
             $totalProgress->setMessage('Numerating...');
             $totalProgress->start();
         }
         /** @var Journal $journal */
         foreach ($journals as $journal) {
             $articles = $entityManager->getRepository('OjsJournalBundle:Article')->findBy(['journal' => $journal]);
             $totalProgress->setMessage('Numerating articles of "' . $journal->getTitle() . '"');
             foreach ($articles as $article) {
                 NumeratorHelper::numerateArticle($article, $entityManager);
             }
             $totalProgress->advance();
         }
         $totalProgress->finish();
         $output->writeln('');
         // Necessary, unfortunately.
         $output->writeln('<info>Done.</info>');
     } else {
         if ($entity === 'issue') {
             $output->writeln('<comment>This might take a while.</comment>');
             $journals = $entityManager->getRepository('OjsJournalBundle:Journal')->findAll();
             $totalProgress = new ProgressBar($output, count($journals));
             $totalProgress->setFormat('%current%/%max% [%bar%] %message%');
             if ($totalProgress->getMaxSteps() > 0) {
                 $totalProgress->setMessage('Numerating...');
                 $totalProgress->start();
             }
             /** @var Journal $journal */
             foreach ($journals as $journal) {
                 $issues = $entityManager->getRepository('OjsJournalBundle:Issue')->findBy(['journal' => $journal]);
                 $totalProgress->setMessage('Numerating issues of "' . $journal->getTitle() . '"');
                 foreach ($issues as $issue) {
                     NumeratorHelper::numerateIssue($issue, $entityManager);
                 }
                 $totalProgress->advance();
             }
             $totalProgress->finish();
             $output->writeln('');
             // Necessary, unfortunately.
             $output->writeln('<info>Done.</info>');
         } else {
             $output->writeln('<error>This entity is not yet supported.</error>');
         }
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $defaultEntityManager = $this->getContainer()->get('doctrine.orm.default_entity_manager');
     $legacyEntityManager = $this->getContainer()->get('doctrine.orm.legacy_entity_manager');
     $legacyCommentsRepository = $legacyEntityManager->getRepository('LegacyBundle:Comment');
     $legacyParameterRepository = $legacyEntityManager->getRepository('LegacyBundle:Parameter');
     $authorRepository = $defaultEntityManager->getRepository('AppBundle:Author');
     $mentionRepository = $defaultEntityManager->getRepository('AppBundle:Mention');
     $legacyComments = $legacyCommentsRepository->findAll();
     $progress = new ProgressBar($output, count($legacyComments));
     $progress->start();
     $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %message%');
     $progress->setMessage('Copying legacy data');
     foreach ($legacyComments as $legacyComment) {
         $userId = $legacyComment->getUser()->getId();
         $author = $authorRepository->findOneBy(['userId' => $userId]);
         if (null === $author) {
             $author = new Author();
             $author->setUserId($legacyComment->getUser()->getId());
             $author->setUsername($legacyComment->getUser()->getUsername());
             $avatarParameter = $legacyParameterRepository->findOneBy(['userId' => $legacyComment->getUser()->getId(), 'parameterId' => 4]);
             if (null !== $avatarParameter) {
                 $author->setAvatarFilename($avatarParameter->getValue());
             }
             $defaultEntityManager->persist($author);
             $defaultEntityManager->flush($author);
         }
         $comment = new Comment();
         $comment->setId($legacyComment->getId());
         $comment->setPostId($legacyComment->getPostId());
         $comment->setContent($legacyComment->getContent());
         $comment->setCreatedAt($legacyComment->getCreatedAt());
         $comment->setActive($legacyComment->getActive());
         $comment->setAuthor($author);
         foreach ($legacyComment->getMentions() as $legacyMention) {
             $mention = $mentionRepository->findOneBy(['userId' => $legacyMention->getUser()->getId()]);
             if (null === $mention) {
                 $mention = new Mention();
                 $mention->setUserId($legacyMention->getUser()->getId());
                 $mention->setUsername($legacyMention->getUser()->getUsername());
                 $defaultEntityManager->persist($mention);
                 $defaultEntityManager->flush($mention);
             }
             $comment->addMention($mention);
         }
         $defaultEntityManager->persist($comment);
         $progress->advance();
     }
     $defaultEntityManager->flush();
     $progress->setMessage('Data has been copied');
     $progress->finish();
     $output->writeln('');
 }
 /**
  * @param array $data
  */
 protected function onStatus(array $data)
 {
     if (isset($data['current'])) {
         $this->progress->setCurrent((int) $data['current']);
         unset($data['current']);
     } else {
         $this->progress->advance();
     }
     foreach ($data as $key => $value) {
         $this->progress->setMessage($value, $key);
     }
 }
 /**
  * Run a terminal command
  * @param  [array]         $command  [description]
  * @param  [path]          $directory [description]
  * @param  OutputInterface $output    [description]
  * @return [void]                     [description]
  */
 private function runProcess($command, $directory, $output, $alias)
 {
     $output->writeln('');
     if (is_array($command['line'])) {
         $commandLine = implode(' && ', $command['line']);
     } else {
         $commandLine = $command['line'];
     }
     $process = new Process($commandLine, $directory);
     $process->setTimeout(7600);
     $process->start();
     if ($output->isVerbose()) {
         $process->wait(function ($type, $buffer) {
             echo $buffer;
         });
     } else {
         $progress = new ProgressBar($output);
         $progress->setFormat("<comment>%message%</comment> [%bar%]");
         $progress->setMessage($command['title']);
         $progress->start();
         $progress->setRedrawFrequency(10000);
         while ($process->isRunning()) {
             $progress->advance();
         }
         $progress->finish();
         $progress->clear();
     }
     $output->writeln('');
     $output->write('<comment>' . $command['title'] . ' </comment><info>√ done</info>');
 }
 /**
  * Shoot the create dojo command into the command bus
  *
  * @param $externalDojo
  */
 private function createDojo($externalDojo)
 {
     $this->progressBar->setMessage('Creating new dojo');
     $this->commandBus->handle($externalDojo);
     $this->progressBar->advance();
     $this->countNew++;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $desde = (int) $input->getArgument('desde');
     $cantidad = 100;
     $progress = null;
     $importador = new ImportadorAgentes($this->getContainer(), $this->getContainer()->get('doctrine')->getManager());
     $importador->Inicializar();
     $progress = new ProgressBar($output, $importador->ObtenerCantidadTotal());
     $progress->setRedrawFrequency(1);
     $progress->setMessage('Importando agentes...');
     $progress->start();
     $ResultadoFinal = new ResultadoImportacion($importador);
     while (true) {
         $resultado = $importador->Importar($desde, $cantidad);
         $ResultadoFinal->AgregarContadoresLote($resultado);
         if (!$resultado->HayMasRegistros()) {
             break;
         }
         $desde += $cantidad;
         $progress->advance($cantidad);
     }
     $progress->finish();
     $output->writeln('');
     $output->writeln(' Se importaron   ' . $ResultadoFinal->RegistrosNuevos . ' registros nuevos.');
     $output->writeln(' Se actualizaron ' . $ResultadoFinal->RegistrosActualizados . ' registros.');
     $output->writeln(' Se ignoraron    ' . $ResultadoFinal->RegistrosIgnorados . ' registros.');
     $output->writeln('Importación finalizada, se procesaron ' . $ResultadoFinal->TotalRegistrosProcesados() . ' registros.');
 }
 /**
  * Get all available regions.
  * @return mixed|null
  */
 protected function getRegions()
 {
     $this->progress->setMessage("Fetching regions...");
     $this->progress->advance();
     $ec2client = new Ec2Client(['version' => 'latest', 'region' => getenv('AWS_DEFAULT_REGION')]);
     return $ec2client->describeRegions()->search('Regions[].RegionName');
 }
 /**
  * TODO change interface to method passing in configuration object (which is validated)
  *
  * Perform a rate-limited API call. The flow is:
  * 1. requestFunction()
  * 2. processFunction() based on requestFunction result
  * 3. publishFunction() based on processFunction result
  *
  * Only requestFunction() and serviceName are required fields.
  *
  * @param $serviceName
  * @param callable $requestFunction should return a list for processing
  * @param callable $processFunction must return a list of models for publishing
  * @param callable $publishFunction method to upload models; responsible for handling publication failures
  * @return mixed
  */
 public function makeRateLimitedRequest($serviceName, $requestFunction, $processFunction = null, $publishFunction = null)
 {
     $rateLimit = self::$rate_limits[$serviceName];
     if (SyncCommandBase::$requests_processed_this_minute[$serviceName] >= $rateLimit) {
         $seconds_to_sleep = 60 - (time() - SyncCommandBase::$start_of_minute_timestamp[$serviceName]);
         if ($seconds_to_sleep > 0) {
             $this->progressBar->setMessage("Rate limit reached for '{$serviceName}'. Waiting {$seconds_to_sleep} seconds.");
             $this->progressBar->display();
             sleep($seconds_to_sleep);
             $this->progressBar->setMessage("");
         }
         SyncCommandBase::$start_of_minute_timestamp[$serviceName] = time();
         SyncCommandBase::$requests_processed_this_minute[$serviceName] = 0;
     } elseif (time() - SyncCommandBase::$start_of_minute_timestamp[$serviceName] > 60) {
         SyncCommandBase::$start_of_minute_timestamp[$serviceName] = time();
         SyncCommandBase::$requests_processed_this_minute[$serviceName] = 0;
     }
     $response = $requestFunction();
     SyncCommandBase::$requests_processed_this_minute[$serviceName]++;
     if ($processFunction != null) {
         /** @var callable $processFunction */
         $processedModels = $processFunction($response);
         if ($publishFunction != null) {
             /** @var callable $publishFunction */
             $publishFunction($processedModels);
         }
     } else {
         // don't do anything
     }
     return $response;
 }
 /**
  * @param int         $current
  * @param PhpFileInfo $file
  */
 public function advance($current, PhpFileInfo $file)
 {
     if (!$this->verbose) {
         return;
     }
     if (1 === $current) {
         $format = '<info>%message%</info>' . "\n" . $this->label . ': <info>%current%</info>/<info>%max%</info>';
         $this->progressBar->clear();
         $this->progressBar->setFormat($format);
     }
     $message = $file->getRelativePathname();
     $this->progressBar->setMessage($message);
     $this->progressBar->clear();
     $this->progressBar->advance();
     $this->progressBar->display();
 }
Beispiel #18
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $startTime = microtime(true);
     $output->writeln("phplint {$this->getApplication()->getVersion()}");
     $output->writeln('');
     $phpBinary = PHP_BINARY;
     $path = $input->getArgument('path');
     $exclude = $input->getOption('exclude');
     $extensions = $input->getOption('extensions');
     $procLimit = $input->getOption('jobs');
     // $failOnFirst = $input->getOption('fail-on-first');
     if ($extensions) {
         $extensions = explode(',', $extensions);
     } else {
         $extensions = array('php');
     }
     $linter = new Linter($path, $exclude, $extensions);
     if ($procLimit) {
         $linter->setProcessLimit($procLimit);
     }
     $files = $linter->getFiles();
     $fileCount = count($files);
     $progress = new ProgressBar($output, $fileCount);
     $progress->setBarWidth(50);
     $progress->setMessage('', 'overview');
     $progress->setFormat(" %overview%\n %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%");
     $progress->start();
     $linter->setProcessCallback(function ($status, $filename) use($progress) {
         /*
         $overview = $progress->getMessage('overview');
         
         if ($status == 'ok') {
             $overview .= '.';
         } elseif ($status == 'error') {
             $overview .= 'F';
             // exit(1);
         }
         
         $progress->setMessage($overview, 'overview');
         */
         $progress->advance();
     });
     $result = $linter->lint($files);
     $progress->finish();
     $output->writeln('');
     $testTime = microtime(true) - $startTime;
     $code = 0;
     $errCount = count($result);
     $out = "<info>Checked {$fileCount} files in " . round($testTime, 1) . " seconds</info>";
     if ($errCount > 0) {
         $out .= "<info> and found syntax errors in </info><error>{$errCount}</error><info> files.</info>";
         $out .= "\n" . json_encode($result, JSON_PRETTY_PRINT);
         $code = 1;
     } else {
         $out .= '<info> a no syntax error were deteced.';
     }
     $output->writeln($out . PHP_EOL);
     return $code;
 }
 /**
  * Ending the install process.
  *
  * @param string $message End message
  */
 public function end($message)
 {
     $this->info($message);
     if ($this->progressBar instanceof ProgressBar) {
         $this->progressBar->setMessage($message);
         $this->progressBar->finish();
     }
 }
 /**
  * @param TransportEvent $event
  */
 public function onPostFetch(TransportEvent $event)
 {
     if ($this->progressActive) {
         $this->progress->finish();
         $this->progressActive = false;
     }
     $this->progress->setMessage(sprintf('Saved to <info>%s</info>', $event->getTransport()->getDestination()));
 }
Beispiel #21
0
 /**
  * Executes the command user:reclean
  *
  * Cleans user names that are unclean.
  *
  * @param InputInterface  $input  The input stream used to get the options
  * @param OutputInterface $output The output stream, used to print messages
  *
  * @return int 0 if all is well, 1 if any errors occurred
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->section($this->language->lang('CLI_USER_RECLEAN_START'));
     $this->processed = 0;
     $this->progress = $this->create_progress_bar($this->get_count(), $io, $output);
     $this->progress->setMessage($this->language->lang('CLI_USER_RECLEAN_START'));
     $this->progress->start();
     $stage = 0;
     while ($stage !== true) {
         $stage = $this->reclean_usernames($stage);
     }
     $this->progress->finish();
     $io->newLine(2);
     $io->success($this->language->lang('CLI_USER_RECLEAN_DONE', $this->processed));
     return 0;
 }
Beispiel #22
0
 /**
  * Setup the progress bar.
  *
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  */
 protected function setupProgressBar(OutputInterface $output)
 {
     $this->progress = new ProgressBar($output, count($this->themes) * count($this->patterns));
     $this->progress->setFormat("<info>%message%</info>\n<fg=red>[</>%bar%<fg=red>]</> <fg=yellow>(%current%/%max%) (%elapsed%)</>");
     $this->progress->setBarCharacter('<fg=blue>#</>');
     $this->progress->setProgressCharacter("<fg=magenta>#</>");
     $this->progress->setMessage('Test');
     $this->progress->start();
 }
 function it_should_advance_progress(ProgressBar $progressBar, TaskEvent $event, TaskInterface $task)
 {
     $event->getTask()->willReturn($task);
     $progressBar->setFormat(Argument::type('string'))->shouldBeCalled();
     $progressBar->setOverwrite(false)->shouldBeCalled();
     $progressBar->setMessage(Argument::type('string'))->shouldBeCalled();
     $progressBar->advance()->shouldBeCalled();
     $this->advanceProgress($event);
 }
 private function getNotificationCallback($filename)
 {
     $notificationCallback = function ($notification_code, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) use($filename) {
         switch ($notification_code) {
             case STREAM_NOTIFY_FILE_SIZE_IS:
                 $this->progress = new ProgressBar($this->output, $bytesMax);
                 $this->progress->setFormat('%message% %final_report%' . "\n" . '%percent:3s%% of %photo_size% [%bar%] %downloaded_bytes% eta %estimated:6s%');
                 $this->progress->setMessage($filename);
                 $this->progress->setMessage('', 'final_report');
                 $this->progress->start();
                 break;
             case STREAM_NOTIFY_PROGRESS:
                 $this->progress->setCurrent($bytesTransferred);
                 break;
         }
     };
     return $notificationCallback;
 }
 /**
  * Search for books
  *
  * @param ProgressBar $progressBar
  * @param string      $query
  * @return array
  */
 public function searchBooks(ProgressBar $progressBar, $query = '')
 {
     $this->countMaxPages($query);
     do {
         $progressBar->setMessage("Page {$this->page}/{$this->maxPages}");
         $slugs = $this->grabSlugs($this->buildSearchUrl($query));
         $this->parseSlugs($progressBar, $slugs);
     } while ($this->page++ != $this->maxPages);
     return $this->books;
 }
Beispiel #26
0
 /**
  * {@inheritdoc}
  */
 public function set_progress($task_lang_key, $task_number)
 {
     parent::set_progress($task_lang_key, $task_number);
     if ($this->progress_bar !== null) {
         $this->progress_bar->setProgress($this->current_task_progress);
         $this->progress_bar->setMessage($this->current_task_name);
     } else {
         $this->output->writeln(sprintf('[%3d/%-3d] %s', $this->current_task_progress, $this->task_progress_count, $this->current_task_name));
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $listPackages = (new NltkCorporaIndexDownloader())->getPackages();
     // create a new progress bar (50 units)
     $progress = new ProgressBar($output, count($listPackages));
     $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
     // start and displays the progress bar
     $progress->start();
     foreach ($listPackages as $package) {
         // ... do some work
         $progress->setMessage("Downloading {$package->getName()}");
         $download = DPF::download($package);
         $progress->setMessage("Package {$package->getId()} - {$package->getName()} was installed into {$download->getInstallDir()}");
         // advance the progress bar 1 unit
         $progress->advance();
     }
     // ensure that the progress bar is at 100%
     $progress->finish();
 }
 function it_finishes_progress_early(OutputInterface $output, ProgressBar $progressBar, RunnerEvent $event)
 {
     $progressBar->getProgress()->willReturn(1);
     $progressBar->getMaxSteps()->willReturn(2);
     $progressBar->setFormat(Argument::type('string'))->shouldBeCalled();
     $progressBar->setMessage(Argument::type('string'))->shouldBeCalled();
     $progressBar->setOverwrite(false)->shouldBeCalled();
     $progressBar->finish()->shouldBeCalled();
     $output->writeln('')->shouldBeCalled();
     $this->finishProgress($event);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $registry = $this->getContainer()->get('doctrine');
     $log = $this->getContainer()->get('logger');
     $em = $registry->getManager('eve_data');
     $eveRegistry = $this->getContainer()->get('evedata.registry');
     $client = new Client(['base_uri' => 'https://public-crest.eveonline.com/']);
     $items = $eveRegistry->get('EveBundle:ItemType')->findAllMarketItems();
     // regions we actually need
     $configs = $registry->getManager()->getRepository('AppBundle:BuybackConfiguration')->findBy(['type' => BuybackConfiguration::TYPE_REGION]);
     $neededRegions = array_reduce($configs, function ($carry, $value) {
         if ($carry === null) {
             return $value->getRegions();
         }
         return array_merge($carry, $value->getRegions());
     });
     $progress = new ProgressBar($output, count($neededRegions) * count($items));
     $progress->setFormat('<comment> %current%/%max% </comment>[%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% <question>%memory:6s%</question> <info> %message% </info>');
     $itemPriceRepo = $em->getRepository('EveBundle:ItemPrice');
     $existing = $itemPriceRepo->findAll();
     $log->addDebug("Flushing existing items");
     foreach ($existing as $i) {
         $em->remove($i);
     }
     $em->flush();
     $log->addDebug("Beginning Import");
     foreach ($neededRegions as $r) {
         $r = $eveRegistry->get('EveBundle:Region')->getRegionById($r);
         $progress->setMessage("Processing Region {$r['regionName']}");
         foreach ($items as $k => $i) {
             $url = $this->getCrestUrl($r['regionID'], $i['typeID']);
             try {
                 $response = $client->get($url);
                 $obj = json_decode($response->getBody()->getContents(), true);
                 $processableItem = array_pop($obj['items']);
                 if (is_array($processableItem)) {
                     $p = $this->makePriceData($processableItem, $r, $i);
                     $em->persist($p);
                     $log->addDebug("Adding item {$p->getTypeName()} in {$p->getRegionName()}");
                 }
             } catch (\Exception $e) {
                 $log->addError(sprintf("Failed request for : %s with %s", $url, $e->getMessage()));
             }
             $progress->advance();
             if ($k % 500 === 0) {
                 $em->flush();
                 $em->clear();
             }
         }
     }
     $em->flush();
     $em->clear();
     $progress->finish();
 }
 public function setMessage($message, $name = 'message', $display = true)
 {
     $diff = strlen($this->last_message) - strlen($message);
     $this->last_message = $message;
     if ($diff > 0) {
         $message .= str_repeat(' ', $diff + 10);
     }
     parent::setMessage($message, $name);
     if ($display) {
         $this->display();
     }
 }