finish() public method

Finishes the progress output.
public finish ( )
Beispiel #1
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 finish()
 {
     if ($this->progressBar !== null) {
         $this->progressBar->finish();
         $this->output->writeln('');
     }
 }
Beispiel #3
0
 /**
  * Execute the generator command.
  *
  * @param \Symfony\Component\Console\Input\InputInterface   $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  *
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->themes = $this->loadThemes();
     $this->patterns = $this->loadPatterns();
     $this->setupProgressBar($output);
     $twig = new Twig_Environment(new Twig_Loader_Filesystem(BASE_PATH . '/resources/files'));
     foreach ($this->themes as $theme) {
         $theme->year = date('Y');
         $theme->uuid = Uuid::uuid4()->toString();
         foreach ($this->patterns as $pattern) {
             $this->progress->setMessage("Generating '{$theme->theme->name}' theme for '{$pattern->name}'.");
             foreach ($pattern->files as $source => $destination) {
                 $result = $twig->render($source, (array) $theme);
                 $destination = str_replace('{{theme}}', $theme->theme->slug, $destination);
                 if (count($pattern->files) > 1) {
                     $output = BASE_PATH . "/output/{$pattern->slug}/{$theme->theme->slug}/{$destination}";
                 } else {
                     $output = BASE_PATH . "/output/{$pattern->slug}/{$destination}";
                 }
                 @mkdir(dirname($output), 0777, true);
                 file_put_contents($output, $result);
             }
             $this->progress->advance();
         }
     }
     $this->progress->setMessage("Enjoy the themes!");
     $this->progress->finish();
 }
 /**
  * Download the file to the specified path
  * @return string path to the downloaded file
  */
 public function download()
 {
     if (!ini_get('allow_url_fopen')) {
         throw new Exception('allow_url_fopen is disabled.');
     }
     // open the temp file for writing
     $fileHandle = fopen($this->path, 'wb');
     if ($fileHandle === false) {
         throw new Exception('Could not open temp file.');
     }
     // download context so we can track download progress
     $downloadContext = stream_context_create(array(), array('notification' => array($this, 'showDownloadProgress')));
     // open the download url for reading
     $downloadHandle = @fopen($this->url, 'rb', false, $downloadContext);
     if ($downloadHandle === false) {
         throw new Exception('Could not download installation file.');
     }
     while (!feof($downloadHandle)) {
         if (fwrite($fileHandle, fread($downloadHandle, 1024)) === false) {
             throw new Exception('Could not write installation file to disk.');
         }
     }
     fclose($downloadHandle);
     fclose($fileHandle);
     if ($this->progressBar) {
         $this->progressBar->finish();
         $this->output->writeln('');
     }
     return $this->path;
 }
 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);
 }
 /**
  * @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()));
 }
 public function end()
 {
     if (!$this->verbose) {
         return;
     }
     $this->progressBar->clear();
     $this->progressBar->finish();
 }
Beispiel #8
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 #9
0
 /**
  * {@inheritdoc}
  */
 protected function fire()
 {
     $tasks = $this->craft->tasks->getAllTasks();
     if (!$tasks) {
         $this->info('No pending tasks.');
         return;
     }
     foreach ($tasks as $task) {
         if ($task->status === TaskStatus::Running) {
             if ($this->option('reset-running')) {
                 $this->resetTask($task);
             } else {
                 continue;
             }
         }
         if ($task->status === TaskStatus::Error) {
             if ($this->option('reset-failed')) {
                 $this->resetTask($task);
             } else {
                 continue;
             }
         }
         try {
             $taskRecord = TaskRecord::model()->findById($task->id);
             $taskType = $task->getTaskType();
             if (!$taskType) {
                 throw new Exception('Could not find task type for task ID ' . $task->id);
             }
             $task->totalSteps = $taskType->getTotalSteps();
             $task->status = TaskStatus::Running;
             $progressBar = new ProgressBar($this->output, $task->totalSteps);
             $this->info($task->description);
             for ($step = 0; $step < $task->totalSteps; $step++) {
                 $task->currentStep = $step + 1;
                 $this->craft->tasks->saveTask($task);
                 $result = $taskType->runStep($step);
                 if ($result !== true) {
                     $error = is_string($result) ? $result : 'Unknown error';
                     $progressBar->finish();
                     $this->line('');
                     throw new Exception($error);
                 }
                 $progressBar->setProgress($task->currentStep);
             }
             $taskRecord->deleteNode();
             $progressBar->finish();
             $this->line('');
         } catch (Exception $e) {
             $this->failTask($task);
             $this->error($e->getMessage());
         }
     }
     $this->info('All tasks finished.');
 }
Beispiel #10
0
 /**
  * @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;
 }
 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>");
 }
Beispiel #12
0
 /**
  * @param $args
  */
 public function output($args)
 {
     switch ($args['type']) {
         case 'message':
             $this->output->writeln($args['message']);
             break;
         case 'progress':
             if ($args['complete']) {
                 $this->progress->finish();
             } else {
                 $this->progress->advance();
             }
             break;
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!Loader::includeModule('search')) {
         throw new BitrixException('Search module is not installed');
     }
     $searchResult = array();
     $bar = new ProgressBar($output, 0);
     do {
         $bar->display();
         $searchResult = \CSearch::ReIndexAll($input->getOption('full'), static::UPDATE_TIME, $searchResult);
         $bar->advance();
         $bar->clear();
         if (is_array($searchResult) && $searchResult['MODULE'] == 'main') {
             list(, $path) = explode("|", $searchResult["ID"], 2);
             $output->writeln("\r       " . $path, OutputInterface::VERBOSITY_VERBOSE);
         }
     } while (is_array($searchResult));
     $bar->finish();
     $bar->clear();
     $output->write("\r");
     if (ModuleManager::isModuleInstalled('socialnetwork')) {
         $output->writeln('<info>The Social Network module needs to be reindexed using the Social Network component in the public section of site.</info>');
     }
     $output->writeln(sprintf('<info>Reindexed</info> %d element%s.', $searchResult, $searchResult > 1 ? 's' : ''));
     return 0;
 }
 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;
 }
 public function fire()
 {
     if (!$this->option('verbose')) {
         $this->output = new NullOutput();
     }
     if (is_dir(Config::get('laravel-lucene-search.index.path'))) {
         $this->call('search:clear');
     }
     /** @var Search $search */
     $search = App::make('search');
     $modelRepositories = $search->config()->modelRepositories();
     if (count($modelRepositories) > 0) {
         foreach ($modelRepositories as $modelRepository) {
             $this->info('Creating index for model: "' . get_class($modelRepository) . '"');
             $all = $modelRepository->all();
             $count = count($all);
             if ($count > 0) {
                 /** @var ProgressBar $progress */
                 $progress = new ProgressBar($this->getOutput(), $count);
                 foreach ($all as $model) {
                     $search->update($model);
                     $progress->advance();
                 }
                 $progress->finish();
             } else {
                 $this->comment(' No available models found. ');
             }
         }
         $this->info(PHP_EOL . 'Operation is fully complete!');
     } else {
         $this->error('No models found in config file..');
     }
 }
 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.');
 }
Beispiel #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");
 }
 /**
  * @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));
         }
     }
 }
 public function import($file, OutputInterface $output)
 {
     $csvFile = new CsvFile($file);
     $csv = $csvFile->getCsv();
     $progress = new ProgressBar($output, 100);
     $progress->start();
     $cpt = 0;
     $cptTotal = 0;
     foreach ($csv as $data) {
         $etablissement = $this->createFromImport($data, $output);
         if (!$etablissement) {
             continue;
         }
         $this->dm->persist($etablissement);
         $cptTotal++;
         if ($cptTotal % (count($csv) / 100) == 0) {
             $progress->advance();
         }
         if ($cpt > 1000) {
             $this->dm->flush();
             $this->dm->clear();
             gc_collect_cycles();
             $cpt = 0;
         }
         $cpt++;
     }
     $this->dm->flush();
     $progress->finish();
 }
 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)
 {
     $this->configuration = $this->getHelperSet()->get('configuration')->getConfiguration();
     $this->entityManager = $this->getHelperSet()->get('em')->getEntityManager();
     $this->questionHelper = $this->getHelperSet()->get('question');
     if (!empty($this->configuration['assetsProcessing']['maxPixelSize']) && $this->configuration['assetsProcessing']['maxPixelSize'] > 0) {
         $this->downscaler = new DownscaleImageManager($this->entityManager, null, $this->configuration['assetsProcessing']['driver'], $this->configuration['assetsProcessing']['maxPixelSize']);
         $confirmation = new ConfirmationQuestion('<question>Are you sure to downscale all your image documents to ' . $this->configuration['assetsProcessing']['maxPixelSize'] . 'px?</question>', false);
         if ($this->questionHelper->ask($input, $output, $confirmation)) {
             $documents = $this->entityManager->getRepository('RZ\\Roadiz\\Core\\Entities\\Document')->findBy(['mimeType' => ['image/png', 'image/jpeg', 'image/gif', 'image/tiff'], 'raw' => false]);
             $progress = new ProgressBar($output, count($documents));
             $progress->setFormat('verbose');
             $progress->start();
             foreach ($documents as $document) {
                 $this->downscaler->processDocumentFromExistingRaw($document);
                 $progress->advance();
             }
             $progress->finish();
             $text = PHP_EOL . '<info>Every documents have been downscaled, a raw version has been kept.</info>' . PHP_EOL;
             /*
              * Clear cache documents
              */
             $assetsClearer = new AssetsClearer();
             $assetsClearer->clear();
             $text .= $assetsClearer->getOutput() . PHP_EOL;
         }
     } else {
         $text = '<info>Your configuration is not set for downscaling documents.</info>' . PHP_EOL;
         $text .= 'Add <info>assetsProcessing.maxPixelSize</info> parameter in your <info>config.yml</info> file.' . PHP_EOL;
     }
     $output->writeln($text);
 }
 /**
  * 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>');
 }
Beispiel #26
0
 /**
  * @param OutputInterface $output
  * @param Query $query
  * @param string $name
  * @param bool $force
  * @param bool $noProgress
  * @return void
  * @throws \Exception
  */
 protected function generate(OutputInterface $output, Query $query, $name, $force, $noProgress)
 {
     $use = implode(', ', $query->getProviders());
     if (!$force && $query->exists()) {
         $output->writeln("<comment>use exist {$name} table.</comment>", OutputInterface::VERBOSITY_VERBOSE);
     } else {
         $output->writeln("<info>generate {$name} table with {$use}:</info>");
         if (!$noProgress) {
             $query->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 {
             $query->init();
         }
         $output->writeln('<info> completed!</info>');
     }
 }
Beispiel #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('');
 }
Beispiel #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();
 }
Beispiel #30
0
 /**
  * (non-PHPdoc)
  *
  * @see \Symfony\Component\Console\Command\Command::execute()
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $document = $this->getDocument($input->getArgument('document'));
     $items = $document->getElement();
     $directory = sprintf($input->getArgument('elementOutput'), $document->getFileInfo()->getBasename('.dtd'));
     $namespace = sprintf($input->getArgument('elementNamespace'), $document->getFileInfo()->getBasename('.dtd'));
     $parentClass = $input->getArgument('elementParentClass');
     $description = str_replace("\\", " ", $namespace);
     if (!file_exists($directory)) {
         mkdir($directory, 0777, true);
     }
     $progressBar = new ProgressBar($output, $items->count());
     $progressBar->setFormat('verbose');
     foreach ($items as $item) {
         $name = sprintf("%sElement", Source::camelCase($item->getName()));
         $filename = sprintf("%s/%s.php", $directory, $name);
         $classDescription = sprintf("%s %s", $description, $name);
         $datetime = new \DateTime();
         $properties = array((new PropertyGenerator("name", $item->getName()))->setDocBlock(new DocBlockGenerator(sprintf("%s Name", $classDescription), "", array(new Tag("var", "string")))), (new PropertyGenerator("value", $item->getValue()))->setDocBlock(new DocBlockGenerator(sprintf("%s Value", $classDescription), "", array(new Tag("var", "string")))));
         $docblock = new DocBlockGenerator($classDescription, "", array(new Tag("author", "ITC Generator " . $datetime->format("d.m.Y h:m:s")), new Tag("copyright", "LGPL")));
         $fileGenerator = new FileGenerator();
         $fileGenerator->setClass(new ClassGenerator($name, $namespace, null, $parentClass, array(), $properties, array(), $docblock));
         file_put_contents($filename, $fileGenerator->generate());
         $progressBar->advance();
     }
     $progressBar->finish();
 }