start() public méthode

Starts the progress output.
public start ( integer | null $max = null )
$max integer | null Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
 protected function test($count, $classes, OutputInterface $output)
 {
     $this->table = new Table($output);
     $this->table->setHeaders(array('Implementation', 'Memory', 'Duration'));
     $output->writeln(sprintf('<info>%d elements</info>', $count));
     $this->process = new ProgressBar($output, count($classes));
     $this->process->start();
     foreach ($classes as $class) {
         $shortClass = $class;
         //            if (in_array($class, $blacklist)) {
         //                $this->table->addRow([$class, '--', '--']);
         //                continue;
         //            };
         $path = __DIR__ . '/../../bin/test.php';
         $result = `php {$path} {$class} {$count}`;
         $data = json_decode($result, true);
         if (!$data) {
             echo $result;
         }
         $this->table->addRow([$shortClass, sprintf('%11sb', number_format($data['memory'])), sprintf('%6.4fs', $data['time'])]);
         $this->process->advance();
     }
     $this->process->finish();
     $output->writeln('');
     $this->table->render($output);
 }
 /**
  * {@inheritdoc}
  */
 public function prepare()
 {
     $this->progress = new ProgressBar($this->output, $this->reader->count());
     $this->progress->setFormat($this->verbosity);
     $this->progress->setRedrawFrequency($this->redrawFrequency);
     $this->progress->start();
 }
Exemple #3
0
 /**
  * {@inheritdoc}
  */
 public function start()
 {
     $dispatcher = $this->getDispatcher();
     $sourceEvent = new SourcePipelineEvent();
     $sourceEvent->setContext($this->getContext());
     $dispatcher->dispatch($this->getEventName(self::EVENT_SUFFIX_SOURCE), $sourceEvent);
     $this->setContext($sourceEvent->getContext());
     $sources = $sourceEvent->getSources();
     $outputs = [];
     $startEvent = new StartPipelineEvent();
     $startEvent->setContext($this->getContext());
     $startEvent->setItemCount($this->countSourceItems($sources));
     $dispatcher->dispatch($this->getEventName(self::EVENT_SUFFIX_START), $startEvent);
     $this->setContext($startEvent->getContext());
     $this->progressBar && $this->progressBar->start($this->countSourceItems($sources));
     foreach ($sources as $source) {
         foreach ($source as $item) {
             $itemEvent = new ItemPipelineEvent($item);
             $itemEvent->setContext($this->getContext());
             $dispatcher->dispatch($this->getEventName(self::EVENT_SUFFIX_MODIFY), $itemEvent);
             $dispatcher->dispatch($this->getEventName(self::EVENT_SUFFIX_CONSUME), $itemEvent);
             $output = $itemEvent->getOutput();
             if ($output !== null) {
                 $outputs[] = $output;
             }
             $this->setContext($itemEvent->getContext());
             $this->progressBar && $this->progressBar->advance();
         }
     }
     $finishEvent = new FinishPipelineEvent();
     $finishEvent->setContext($this->getContext());
     $dispatcher->dispatch($this->getEventName(self::EVENT_SUFFIX_FINISH), $finishEvent);
     $this->progressBar && $this->progressBar->finish();
     return ['outputs' => $outputs];
 }
 public function run(OutputInterface $output)
 {
     $output->writeln('**********************************');
     $output->writeln('Starting sync for dojos');
     $this->progressBar = $this->newProgressBar($output);
     $externalDojos = $this->zen->getDojos();
     $this->progressBar->start(count($externalDojos));
     $this->progressBar->setMessage('Iterating dojos...');
     foreach ($externalDojos as $externalDojo) {
         $this->progressBar->setMessage('Handling ' . $externalDojo->getName());
         if (true === $externalDojo->isRemoved()) {
             $this->removeInternalDojo($externalDojo);
             continue;
         }
         try {
             $internalDojo = $this->getInternalDojo($externalDojo->getZenId(), $externalDojo->getCity(), $externalDojo->getTwitter(), $externalDojo->getEmail());
         } catch (NonUniqueResultException $exception) {
             $this->unmatched[] = $externalDojo;
             continue;
         }
         if (null !== $internalDojo) {
             $this->updateInternalDojo($internalDojo, $externalDojo);
             continue;
         }
         $this->createDojo($externalDojo);
     }
     $this->progressBar->setMessage('Flushing');
     $this->doctrine->flush();
     $this->progressBar->setMessage('Finished syncing dojos!');
     $this->progressBar->finish();
     $output->writeln($this->countNew . ' New dojos added');
     $output->writeln($this->countUpdated . ' Existing dojos updated');
     $output->writeln($this->countRemoved . ' Existing dojos removed');
     $this->notifySlack();
 }
Exemple #5
0
 /**
  * @param RunnerEvent $event
  */
 public function startProgress(RunnerEvent $event)
 {
     $numberOftasks = $event->getTasks()->count();
     $this->progressBar->setFormat('<fg=yellow>%message%</fg=yellow>');
     $this->progressBar->setMessage('GrumPHP is sniffing your code!');
     $this->progressBar->start($numberOftasks);
 }
 /**
  * @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);
 }
 /**
  * Starting the install process.
  *
  * @param string $message  Start message
  * @param int    $maxSteps The number of steps that will be taken
  */
 public function start($message, $maxSteps)
 {
     $this->info($message);
     if ($this->progressBar instanceof ProgressBar) {
         $this->progressBar->setMessage($message);
         $this->progressBar->start($maxSteps);
     }
 }
 private function progressBarInit($count)
 {
     if ($this->progressBar === null) {
         return;
     }
     $this->progressBar->start($count);
     $this->progressBar->setBarCharacter(Constants::CHARACTER_PROGRESS_BAR);
     $this->progressBar->setProgressCharacter(Constants::CHARACTER_BEER);
 }
 protected function startProgress($num = 2)
 {
     if (!$this->getOutput()) {
         throw new \Exception('Unable to find console output object.');
     }
     $this->bar = new ProgressBar($this->getOutput(), $num);
     $this->bar->setFormat("%message%\n [%bar%] %percent:3s%% %elapsed% %memory:6s% ");
     $this->bar->start();
 }
 /**
  * @param int $total
  */
 public function start($total)
 {
     if (!$this->verbose) {
         return;
     }
     $format = $this->label . ': <comment>loading %max% files into memory, this can take some time</comment>';
     $this->progressBar->setFormat($format);
     $this->progressBar->start($total);
 }
 /**
  * @param TransportEvent $event
  */
 public function onPreFetch(TransportEvent $event)
 {
     $size = $event->getTransport()->getSize();
     if ($event->getTransport() instanceof ProgressAwareInterface && $size > 0) {
         $this->progress->start($size);
         $this->progressActive = true;
     }
     $this->progress->setMessage(sprintf('Downloading <info>%s</info> (%s KB)', (string) $event->getTransport(), $size > 0 ? number_format(round($size / 1024), 0, ',', '.') : 'unknown'));
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return null|int null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $config = Config::getInstance();
     $noProgress = $input->getOption('no-progress');
     $query = $input->getArgument('query');
     $provider = $config->getQuery($query);
     if (empty($provider)) {
         $output->writeln("<error>cannot found query \"{$query}\"</error>");
         $output->writeln("<info>you can execute \"</info>ipv4 edit<info>\" to configure the query</info>");
         return 1;
     }
     $type = $input->getOption('type');
     $filename = $config->getFilename($input->getArgument('filename'));
     $export = ExportQuery::create($type, $filename);
     if (empty($export)) {
         $output->writeln("<error>cannot found export query \"{$type}\"</error>");
         return 2;
     }
     $export->setProviders([$provider]);
     $encoding = $input->getOption('encoding');
     if (!empty($encoding)) {
         $export->setEncoding($encoding);
     }
     $ecdz = $input->getOption('ecdz');
     if ($ecdz && method_exists($export, 'setEcdz')) {
         $export->setEcdz($ecdz);
     }
     $remove_ip_in_recode = $input->getOption('remove-ip-in-recode');
     if ($remove_ip_in_recode && method_exists($export, 'setRemoveIpInRecode')) {
         $export->setRemoveIpInRecode($remove_ip_in_recode);
     }
     $output->writeln("<info>export \"{$query}\" to \"{$type}\" filename \"{$filename}\":</info>");
     if (!$noProgress) {
         $export->init(function ($code, $n) use($output) {
             switch ($code) {
                 case 0:
                     $this->progress = new ProgressBar($output, $n);
                     $this->progress->start();
                     break;
                 case 1:
                     $this->progress->setProgress($n);
                     break;
                 case 2:
                     $this->progress->finish();
                     break;
             }
         });
     } else {
         $export->init();
     }
     $output->writeln('<info> completed!</info>');
     return 0;
 }
 /**
  * @param string $type
  * @param string $buffer
  */
 public function __invoke(string $type, string $buffer)
 {
     if ($type === 'err' && preg_match('/^-n\\s*\\d+\\s*\\/\\s*(\\d+)\\s*\\((\\d+)\\)\\s*$/', $buffer, $matches)) {
         if ($this->progressBar === null) {
             $this->progressBar = new ProgressBar($this->output, (int) $matches[1]);
             $this->progressBar->setBarWidth(100);
             $this->progressBar->start();
         }
         $this->progressBar->advance();
         $this->updates = $matches[2];
     }
 }
 private function setDownloadWithProgressBar()
 {
     $emitter = $this->httpClient->getEmitter();
     $emitter->on('before', function (\GuzzleHttp\Event\BeforeEvent $event) {
         echo $event->getRequest();
     });
     $emitter->once('progress', function (\GuzzleHttp\Event\ProgressEvent $event) {
         $this->progressBar->start($event->downloadSize);
     });
     $emitter->on('progress', function (\GuzzleHttp\Event\ProgressEvent $event) {
         $this->progressBar->setProgress($event->downloaded);
     });
 }
 public function invoke(ElasticPopulator $populator)
 {
     $begin = function ($total) {
         $this->bar = new ProgressBar($this->out, $total);
         $this->bar->start();
     };
     $tick = function () {
         $this->bar->advance();
     };
     $rows = $populator->populate($begin, $tick);
     $this->bar->finish();
     $this->out->write("\n");
     $this->out->writeln("<info>Reindexed {$rows} rows</info>");
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $indexName = $input->getOption('index');
     $batchSize = $input->getOption('batch_size');
     $indexManager = $this->getIndexManager($indexName);
     $totalDocuments = $indexManager->getTotalEntities();
     $iterations = $this->getIterations($totalDocuments, $batchSize);
     $output->writeln(sprintf('<info>Reindexing</info> "%s"', $indexName));
     $output->writeln(sprintf('<comment>Total documents:</comment> %s', $totalDocuments));
     $output->writeln(sprintf('<comment>Batch size:</comment> %s', $batchSize));
     $output->writeln(sprintf('<comment>Iterations:</comment> %s', $iterations));
     $progress = new ProgressBar($output, $totalDocuments);
     $progress->setFormat('verbose');
     $progress->setRedrawFrequency($batchSize);
     $progress->start();
     $indexManager->purgeIndex();
     for ($i = 0; $i < $iterations; $i++) {
         $criteria = new Criteria();
         $criteria->setMaxResults($batchSize);
         $criteria->setFirstResult($i * $batchSize);
         $collection = $indexManager->getEntitiesCollection($criteria);
         $collection->map(function (EntityInterface $entity) use($indexManager, $progress) {
             $indexManager->addEntity($entity);
             $progress->advance();
         });
     }
     $progress->finish();
     $output->writeln('');
     $output->writeln(sprintf('<info>Optimizing "%s"</info>', $indexName));
     $indexManager->optimizeIndex();
 }
 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.');
 }
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $progress = new ProgressBar($output, 30);
     $entities = $this->getContainer()->getParameter('bigfoot_migrate');
     $transRepo = $this->getContainer()->get('bigfoot_core.translation.repository');
     $output->writeln('<info>Migrating translations...</info>');
     foreach ($entities as $objectClass) {
         $output->writeln('');
         $output->writeln(sprintf('<info>Importing entity: %s</info>', $objectClass));
         $translations = $this->getEntityManager()->getRepository('GedmoTranslatable:Translation')->createQueryBuilder('t')->where('t.objectClass = :objectClass')->setParameter('objectClass', $objectClass)->getQuery()->getArrayResult();
         if ($translations) {
             $progress->start($output, count($translations));
             foreach ($translations as $translation) {
                 $originalElement = $this->getRepository($objectClass)->findOneById($translation['foreignKey']);
                 if ($originalElement) {
                     $transRepo->translate($originalElement, $translation['field'], $translation['locale'], $translation['content']);
                     $this->getEntityManager()->persist($originalElement);
                     $this->getEntityManager()->flush();
                 }
                 $this->getEntityManager()->clear();
                 unset($translationEntity);
                 $progress->advance();
             }
             $progress->finish();
         } else {
             $output->writeln(sprintf('<error>No translation found for entity: %s</error>', $objectClass));
         }
         if ($input->getOption('delete') == true) {
             $this->getEntityManager()->getRepository('GedmoTranslatable:Translation')->createQueryBuilder('t')->delete()->where('t.objectClass = :objectClass')->setParameter('objectClass', $objectClass)->getQuery()->getResult();
             $output->writeln(sprintf('<info>ext_translations of entity: %s have been deleted</info>', $objectClass));
         }
     }
 }
Exemple #19
0
 public function handleRepairFeedBack($event)
 {
     if (!$event instanceof GenericEvent) {
         return;
     }
     switch ($event->getSubject()) {
         case '\\OC\\Repair::startProgress':
             $this->progress->start($event->getArgument(0));
             break;
         case '\\OC\\Repair::advance':
             $this->progress->advance($event->getArgument(0));
             break;
         case '\\OC\\Repair::finishProgress':
             $this->progress->finish();
             $this->output->writeln('');
             break;
         case '\\OC\\Repair::step':
             $this->output->writeln(' - ' . $event->getArgument(0));
             break;
         case '\\OC\\Repair::info':
             $this->output->writeln('     - ' . $event->getArgument(0));
             break;
         case '\\OC\\Repair::warning':
             $this->output->writeln('     - WARNING: ' . $event->getArgument(0));
             break;
         case '\\OC\\Repair::error':
             $this->output->writeln('     - ERROR: ' . $event->getArgument(0));
             break;
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $shopId = $input->getArgument('shopId');
     if (!empty($shopId)) {
         $shopIds[] = $shopId;
     } else {
         $shopIds = $this->container->get('db')->fetchCol('SELECT id FROM s_core_shops WHERE active = 1');
     }
     /** @var \Shopware\Components\HttpCache\CacheWarmer $cacheWarmer */
     $cacheWarmer = $this->container->get('http_cache_warmer');
     foreach ($shopIds as $shopId) {
         $limit = 10;
         $offset = 0;
         $totalUrlCount = $cacheWarmer->getAllSEOUrlCount($shopId);
         $output->writeln("\n Calling URLs for shop with id " . $shopId);
         $progressBar = new ProgressBar($output, $totalUrlCount);
         $progressBar->setBarWidth(100);
         $progressBar->start();
         while ($offset < $totalUrlCount) {
             $urls = $cacheWarmer->getAllSEOUrls($shopId, $limit, $offset);
             $cacheWarmer->callUrls($urls, $shopId);
             $progressBar->advance(count($urls));
             $offset += count($urls);
         }
         $progressBar->finish();
     }
     $output->writeln("\n The HttpCache is now warmed up");
 }
 function execute(InputInterface $input, OutputInterface $output)
 {
     $parameters = $this->extractArgumentsAndOptions($input);
     //如果当前目录下有配置文件自动加载配置文件
     if (is_file($configFile = getcwd() . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
         $data = json_decode(file_get_contents($configFile), true);
         $parameters = array_merge($parameters, $data);
     }
     call_user_func_array([$this, 'initializeCollector'], $parameters);
     $this->collector->getDispatcher()->bind(Collector::EVENT_CAPTURE_URL_REPOSITORY, function (Event $event) use($output) {
         $repository = $event->getArgument('repository');
         $output->writeln(PHP_EOL);
         $output->writeln($repository->getUrl()->getUrlString());
         $progressBar = new ProgressBar($output, 100);
         $progressBar->start();
         $repository->getUrl()->setParameter('progressBar', $progressBar);
     });
     $this->collector->getDispatcher()->bind(Collector::EVENT_CAPTURED_URL_REPOSITORY, function (Event $event) use($output) {
         $repository = $event->getArgument('repository');
         $progressBar = $repository->getUrl()->getParameter('progressBar');
         $progressBar->advance(50);
         $progressBar->finish();
     });
     $this->collector->run();
 }
Exemple #22
0
 private function startProgressBar($max = 0)
 {
     if (null == $this->progressBar) {
         return;
     }
     $this->progressBar->start($max);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->dm = $this->getContainer()->get('doctrine_mongodb.odm.default_document_manager');
     $allContrats = $this->dm->getRepository('AppBundle:Contrat')->findAll();
     $cptTotal = 0;
     $i = 0;
     $progress = new ProgressBar($output, 100);
     $progress->start();
     $nb = count($allContrats);
     foreach ($allContrats as $contrat) {
         if (count($contrat->getMouvements()) > 0) {
             foreach ($contrat->getMouvements() as $contratMvt) {
                 $contratMvt->setTauxTaxe($contrat->getTva());
             }
             $cptTotal++;
             if ($cptTotal % ($nb / 100) == 0) {
                 $progress->advance();
             }
             if ($i >= 1000) {
                 $this->dm->flush();
                 $i = 0;
             }
             $i++;
         }
     }
     $this->dm->flush();
     $progress->finish();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($input->getOption('desde')) {
         $desde = (int) $input->getOption('desde');
     } else {
         $desde = 0;
     }
     if ($input->getOption('hasta')) {
         $hasta = (int) $input->getOption('hasta');
     } else {
         $hasta = 0;
     }
     $output->writeln('Geocodificando partidas...');
     $cantidadTotal = $hasta - $desde;
     $progress = null;
     $em = $this->getContainer()->get('doctrine')->getManager();
     $Helper = new \Yacare\CatastroBundle\Helper\PartidaHelper($this->getContainer(), $em);
     $Partidas = $em->getRepository('Yacare\\CatastroBundle\\Entity\\Partida')->findBy(array('Ubicacion' => null), array('id' => 'ASC'), $desde ?: null, $cantidadTotal ?: null);
     $progress = new ProgressBar($output, count($Partidas));
     $progress->start();
     foreach ($Partidas as $Partida) {
         $Helper->ObtenerGeoCoding($Partida);
         $progress->advance();
         $em->flush();
         // Dormir entre unos segundos entre consulta y consulta
         sleep(rand(10, 20));
     }
     $em->clear();
     $progress->finish();
     $output->writeln('');
     $output->writeln('Geocodificación terminada, se procesaron ' . count($Partidas) . ' registros.');
 }
 /**
  * Download
  */
 protected function download(OutputInterface &$output, $from, $to)
 {
     $output->writeln('Download ' . $from);
     $progress = new ProgressBar($output);
     $progress->setFormat('normal_nomax');
     $step = 0;
     $ctx = stream_context_create(array(), array('notification' => function ($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) use($output, $progress, &$step) {
         switch ($notification_code) {
             case STREAM_NOTIFY_FILE_SIZE_IS:
                 $progress->start(100);
                 break;
             case STREAM_NOTIFY_PROGRESS:
                 $newStep = round($bytes_transferred / $bytes_max * 100);
                 if ($newStep > $step) {
                     $step = $newStep;
                     $progress->setProgress($step);
                 }
                 break;
         }
     }));
     $file = file_get_contents($from, false, $ctx);
     $progress->finish();
     file_put_contents($to, $file);
     $output->writeln('');
     return $to;
 }
 /**
  * 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>');
 }
Exemple #27
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $constraintDescriber = new \RestSpec\Output\ConstraintDescriber();
     $consoleOutput = new \RestSpec\Output\ConsoleOutput($output, $constraintDescriber);
     $validator = new \RestSpec\Validator\Rest();
     $loader = new \RestSpec\Loader();
     $loader->run();
     try {
         $useCaseFilter = $input->getArgument('filter');
         $api = $input->getOption('api');
         $restSpec = Spec\Rest::getInstance();
         $restSpecValidator = new \RestSpec\Spec\Validator();
         $restSpecValidator->validate($restSpec);
         $progressBar = new ProgressBar($output);
         $progressBar->setFormat('Testing your API specs. Already tested: %current% use cases [%bar%]');
         $progressBar->start();
         $validator->progress(function ($useCases) use($output, $progressBar) {
             $progressBar->advance();
         });
         $report = $validator->validate($restSpec, $api, $useCaseFilter);
         $progressBar->finish();
         $output->write($report->dumpAsConsoleText($api, $useCaseFilter));
         if ($report->getTotalUseCases() === 0 || $report->getUseCasesFailedCount() > 0) {
             exit(1);
         } else {
             exit(0);
         }
     } catch (\Exception $e) {
         $log = join("\n", $validator->getLog());
         $consoleOutput->getOutput()->writeln(sprintf("\n<error>Whoops! Some unexpected error occured. Validation log dump:\n\n%s\n\nThe exception type is: %s, and a message is following:</error>", $log, get_class($e)));
         $consoleOutput->errorHandler($e, 2);
     }
 }
 /**
  * Wait for multiple activities to complete.
  *
  * @param Activity[]      $activities
  * @param OutputInterface $output
  */
 public static function waitMultiple(array $activities, OutputInterface $output)
 {
     $count = count($activities);
     if ($count <= 0) {
         return;
     }
     $complete = 0;
     $output->writeln("Waiting...");
     $bar = new ProgressBar($output);
     $bar->start($count);
     $bar->setFormat('verbose');
     while ($complete < $count) {
         sleep(1);
         foreach ($activities as $activity) {
             if (!$activity->isComplete()) {
                 $activity->refresh();
             } else {
                 $complete++;
             }
         }
         $bar->setProgress($complete);
     }
     $bar->finish();
     $output->writeln('');
 }
Exemple #29
0
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $outputFile = $input->getArgument('output');
     $outputHandle = fopen($outputFile, 'w');
     $client = new Client([]);
     $headers = ['Accept' => 'application/json', 'Accept-Encoding' => 'gzip,deflate', 'User-Agent' => 'crossref-dois/0.1 (+https://github.com/hubgit/crossref-dois/)'];
     // https://api.crossref.org/works?filter=type:journal-article&cursor=*
     $filters = ['type' => 'journal-article'];
     $filter = implode(',', array_map(function ($key) use($filters) {
         return $key . ':' . $filters[$key];
     }, array_keys($filters)));
     $params = ['filter' => $filter, 'cursor' => '*', 'rows' => 1000];
     $progress = new ProgressBar($output);
     $progressStarted = false;
     do {
         $response = $client->get('https://api.crossref.org/works', ['connect_timeout' => 10, 'timeout' => 120, 'query' => $params, 'headers' => $headers]);
         $data = json_decode($response->getBody(), true);
         if (!$progressStarted) {
             $progress->start($data['message']['total-results']);
             $progressStarted = true;
         }
         $items = $this->parseResponse($data);
         foreach ($items as $item) {
             fwrite($outputHandle, json_encode($item) . "\n");
         }
         $params['cursor'] = $data['message']['next-cursor'];
         $progress->advance(count($items));
     } while ($params['cursor']);
     $progress->finish();
 }
 private function reindex(string $locale, OutputInterface $output)
 {
     $totalEntities = $this->repository->getTotalCount();
     $iterations = $this->getIterations($totalEntities, $this->batchSize);
     $output->writeln(sprintf('<comment>Total entities:</comment> %s', $totalEntities));
     $output->writeln(sprintf('<comment>Batch size:</comment> %s', $this->batchSize));
     $output->writeln(sprintf('<comment>Iterations:</comment> %s', count($iterations)));
     $output->writeln(sprintf('<comment>Locale:</comment> %s', $locale));
     $output->writeln('<info>Flushing index</info>');
     $this->manager->flushIndex($locale);
     $progress = new ProgressBar($output, $totalEntities);
     $progress->setFormat('verbose');
     $progress->setRedrawFrequency($this->batchSize);
     $progress->start();
     foreach ($iterations as $iteration) {
         $entities = $this->getEntities($iteration);
         foreach ($entities as $entity) {
             $document = $this->type->createDocument($entity, $locale);
             $this->manager->addDocument($document);
             $progress->advance();
         }
     }
     $progress->finish();
     $output->writeln('');
     $output->writeln('<info>Optimizing index</info>');
     $this->manager->optimizeIndex($locale);
 }