advance() public méthode

Advances the progress output X steps.
public advance ( integer $step = 1 )
$step integer Number of steps to advance
Exemple #1
0
 /**
  * {@inheritdoc}
  *
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $buildId = $this->stdIn->getArgument('build');
     $client = new Client(['base_uri' => 'https://api.travis-ci.org/', 'cookies' => true, 'headers' => ['User-Agent' => 'DrupalOrgCli/0.0.1', 'Accept' => 'application/json', 'Accept-Encoding' => '*']]);
     $build = $this->getBuild($client, $buildId);
     $this->stdOut->writeln("<comment>Watching build {$buildId}</comment>");
     $progress = new ProgressBar($this->stdOut);
     $progress->start();
     if ($build->state == 'finished') {
         $progress->advance();
     } else {
         while ($build->state != 'finished') {
             $progress->advance();
             sleep(60);
             $build = $this->getBuild($client, $buildId);
         }
     }
     $progress->finish();
     $this->sendNotification('TravisCI', "TravisCI build {$buildId} completed");
     $this->stdOut->writeln('');
     $table = new Table($this->stdOut);
     $table->setHeaders(['ID', 'Message', 'Result']);
     if ($build->result == 0) {
         $style = 'info';
         $result = 'pass';
     } elseif ($build->result == 1) {
         $style = 'error';
         $result = 'fail';
     } else {
         $style = 'comment';
         $result = 'pending';
     }
     $table->addRow([$buildId, $build->message, "<{$style}>" . $result . "</{$style}>"]);
     $table->render();
 }
Exemple #2
0
 /**
  * {@inheritdoc}
  *
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $jobId = $this->stdIn->getArgument('job');
     $job = $this->client->getPiftJob($jobId);
     $issue = $this->client->getNode($job->get('issue_nid'));
     $this->stdOut->writeln("<comment>" . $issue->get('title') . "</comment>");
     $progress = new ProgressBar($this->stdOut);
     $progress->start();
     if ($job->get('status') == 'complete') {
         $progress->advance();
     } else {
         while ($job->get('status') != 'complete') {
             $progress->advance();
             sleep(60);
             $job = $this->client->getPiftJob($jobId);
         }
     }
     $progress->finish();
     $this->sendNotification('DrupalCI', "DrupalCI test {$jobId} completed");
     $this->stdOut->writeln('');
     $table = new Table($this->stdOut);
     $table->setHeaders(['Job ID', 'Patch', 'Status', 'Result']);
     $patch = $this->client->getFile($job->get('file_id'));
     if ($job->get('result') == 'pass') {
         $style = 'info';
     } elseif ($job->get('result') == 'fail') {
         $style = 'error';
     } else {
         $style = 'comment';
     }
     $table->addRow([$job->get('job_id'), $patch->get('name'), $job->get('status'), "<{$style}>" . $job->get('message') . "</{$style}>"]);
     $table->render();
 }
Exemple #3
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;
 }
 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);
 }
Exemple #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $pBar = new ProgressBar($output, 10);
     $pBar->start();
     $showOutput = false;
     try {
         $sugarKernel = new SugarKernel('cli', 'dev', false);
         $sugarKernel->boot();
     } catch (\Exception $e) {
         $output->writeln($e->getMessage());
     }
     $pBar->advance(2);
     /** @var \User $user */
     $user = $sugarKernel->getG('current_user');
     $user->getSystemUser();
     $modules = $sugarKernel->getG('mod_strings');
     $pBar->advance();
     $qrr = new Qrr();
     if ($input->getOption('yell')) {
         $showOutput = true;
         $output->writeln('QRR output: ');
     }
     $qrr->repairAndClearAll(['clearAll'], [$modules['LBL_ALL_MODULES']], true, $showOutput);
     $pBar->advance(5);
     $sugarKernel->shutdown();
     $pBar->finish();
     $elapsed = time() - $pBar->getStartTime();
     $output->writeln(' ');
     $output->writeln(" Executed in: {$elapsed} s");
 }
 /**
  * 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();
 }
Exemple #7
0
 /**
  * Run the command.
  *
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return void
  * @throws Exception
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $serviceName = $input->getArgument('service');
     $service = $this->serviceManager->getService($serviceName);
     $hostProvider = $service->getHostProvider();
     $this->getApplication()->find('listhosts')->run(new ArrayInput(['service' => $serviceName]), $output);
     $output->writeln("");
     $progress = new ProgressBar($output, 5);
     $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %message%');
     $progress->setMessage('Checking existing hosts');
     $progress->start();
     $currentHostCount = count($hostProvider->getHostsForService($service));
     if ($service->maxHosts && $currentHostCount >= $service->maxHosts) {
         throw new Exception("There are already {$currentHostCount}/{$service->maxHosts} hosts for {$serviceName}.");
     }
     $newInstance = $currentHostCount + 1;
     $hostname = sprintf($service->hostnameTemplate, $newInstance);
     $host = $hostProvider->launch($hostname, $service->hostDefaults);
     $hostname = $host->getHostname();
     // Just check it set the right name
     $progress->setMessage("Created host " . $hostname . " at " . $hostProvider->getName());
     $progress->advance();
     sleep(5);
     $progress->setMessage("Waiting for " . $hostname . " to be ready");
     $progress->advance();
     while (!$host->isReady()) {
         $lastState = $host->getState();
         $progress->setMessage("Waiting for " . $hostname . " to be ready (Current sate: " . $lastState . ")");
         $progress->display();
         sleep(10);
     }
     if (!empty($service->testUrl)) {
         $progress->setMessage("Testing host's HTTP response");
         $progress->advance();
         do {
             $lastResponse = $host->testHttp($service->testUrl, $service->testUrlHeaders);
             $progress->setMessage("Testing host's HTTP response (Current response: {$lastResponse})");
             $progress->display();
             $lastResponse === 200 || sleep(5);
         } while ($lastResponse !== 200);
     }
     $dnsProvider = $service->getDnsProvider();
     $recordData = [];
     foreach ($host->publicIps as $ip) {
         foreach ($service->dnsRecords as $domain => $domainRecords) {
             foreach ($domainRecords as $record => $recordSettings) {
                 $data = ['domain' => $domain, 'type' => $ip->version === 6 ? 'AAAA' : 'A', 'name' => sprintf($record, $newInstance), 'value' => $ip->ip];
                 $recordData[] = $data + $recordSettings;
             }
         }
     }
     $progress->setMessage("Adding " . count($recordData) . " DNS records to " . $dnsProvider->getName());
     $progress->advance();
     $dnsProvider->addRecords($recordData);
     $progress->setMessage('Done!');
     $progress->finish();
     $output->writeln("");
     $output->writeln("");
     $this->getApplication()->find('listhosts')->run(new ArrayInput(['service' => $serviceName]), $output);
 }
Exemple #8
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];
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->setDecorated(true);
     $username = $input->getOption('username');
     $password = $input->getOption('password');
     $plugin = $input->getOption('plugin');
     $lastUpdate = $input->getOption('lastupdate');
     $resource = 'piwik-' . ($plugin ? 'plugin-' . strtolower($plugin) : 'base');
     $transifexApi = new API($username, $password);
     // remove all existing translation files in download path
     $files = glob($this->getDownloadPath() . DIRECTORY_SEPARATOR . '*.json');
     array_map('unlink', $files);
     if (!$transifexApi->resourceExists($resource)) {
         $output->writeln("Skipping resource {$resource} as it doesn't exist on Transifex");
         return;
     }
     $output->writeln("Fetching translations from Transifex for resource {$resource}");
     $availableLanguages = LanguagesManagerApi::getInstance()->getAvailableLanguageNames();
     $languageCodes = array();
     foreach ($availableLanguages as $languageInfo) {
         $languageCodes[] = $languageInfo['code'];
     }
     $languageCodes = array_filter($languageCodes, function ($code) {
         return !in_array($code, array('en', 'dev'));
     });
     try {
         $languages = $transifexApi->getAvailableLanguageCodes();
         if (!empty($plugin)) {
             $languages = array_filter($languages, function ($language) {
                 return LanguagesManagerApi::getInstance()->isLanguageAvailable(str_replace('_', '-', strtolower($language)));
             });
         }
     } catch (AuthenticationFailedException $e) {
         $languages = $languageCodes;
     }
     /** @var ProgressBar $progress */
     $progress = new ProgressBar($output, count($languages));
     $progress->start();
     $statistics = $transifexApi->getStatistics($resource);
     foreach ($languages as $language) {
         try {
             // if we have modification date given from statistics api compare it with given last update time to ignore not update resources
             if (LanguagesManagerApi::getInstance()->isLanguageAvailable(str_replace('_', '-', strtolower($language))) && isset($statistics->{$language})) {
                 $lastupdated = strtotime($statistics->{$language}->last_update);
                 if ($lastUpdate > $lastupdated) {
                     $progress->advance();
                     continue;
                 }
             }
             $translations = $transifexApi->getTranslations($resource, $language, true);
             file_put_contents($this->getDownloadPath() . DIRECTORY_SEPARATOR . str_replace('_', '-', strtolower($language)) . '.json', $translations);
         } catch (\Exception $e) {
             $output->writeln("Error fetching language file {$language}: " . $e->getMessage());
         }
         $progress->advance();
     }
     $progress->finish();
     $output->writeln('');
 }
Exemple #10
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();
 }
 /**
  * {@inheritdoc}
  */
 public function advance($step = 1)
 {
     if ($this->current + $step > $this->count) {
         $step = $this->count - $this->current;
     }
     $this->progress->advance($step);
     $this->current += $step;
 }
 /**
  * Signify the move to the next step in the install.
  *
  * @param string $message Very short message about the step
  */
 public function step($message)
 {
     ++$this->stepCount;
     $this->info($message);
     if ($this->progressBar instanceof ProgressBar) {
         $this->progressBar->setMessage($message);
         $this->progressBar->advance();
     }
 }
Exemple #13
0
 /**
  * {@inheritdoc}
  */
 public function increment($increment = 1)
 {
     if ($this->bar === null) {
         return;
     }
     $this->bar->advance($increment);
     if ($this->bar->getProgress() === $this->bar->getMaxSteps()) {
         $this->consoleIO->getOutput()->writeln(' - Finished!');
     }
 }
Exemple #14
0
 private function advanceProgressBar()
 {
     if (null == $this->progressBar) {
         return;
     }
     try {
         $this->progressBar->advance();
     } catch (RuntimeException $ex) {
         //            var_dump($ex->getMessage());
     }
 }
Exemple #15
0
 /**
  * Copy & Paste Detection (CPD).
  *
  * @param  Iterator|array $files     List of files to process
  * @param  int            $minLines  Minimum number of identical lines
  * @param  int            $minTokens Minimum number of identical tokens
  * @param  bool           $fuzzy
  * @return CodeCloneMap   Map of exact clones found in the list of files
  */
 public function copyPasteDetection($files, $minLines = 5, $minTokens = 70, $fuzzy = false)
 {
     $result = new CodeCloneMap();
     foreach ($files as $file) {
         $this->strategy->processFile($file, $minLines, $minTokens, $result, $fuzzy);
         if ($this->progressBar !== null) {
             $this->progressBar->advance();
         }
     }
     return $result;
 }
 /**
  * @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);
     }
 }
 /**
  * @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];
     }
 }
 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>");
 }
Exemple #19
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;
     }
 }
 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..');
     }
 }
 /**
  * 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>');
 }
 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.');
 }
 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();
 }
Exemple #24
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;
     }
 }
 /**
  * @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));
         }
     }
 }
 /**
  * {@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");
 }
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);
     }
 }
 /**
  * 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');
 }
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();
 }
 /**
  * {@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;
 }