/** * {@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) { $desde = (int) $input->getArgument('desde'); $output->writeln('Importando actividades...'); $cantidad = 100; $progress = null; $importador = new ImportadorActividades($this->getContainer(), $this->getContainer()->get('doctrine')->getManager()); $importador->Inicializar(); $progress = new ProgressBar($output, $importador->ObtenerCantidadTotal()); $progress->start(); $ResultadoFinal = new ResultadoImportacion($importador); while (true) { $resultado = $importador->Importar($desde, $cantidad); $ResultadoFinal->AgregarContadoresLote($resultado); $progress->setProgress($resultado->PosicionCursor()); if (!$resultado->HayMasRegistros()) { break; } $desde += $cantidad; } $progress->finish(); $output->writeln(''); $importador->RecalcularParent($output); $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) { $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); } }
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(); }
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(); }
/** * (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(); }
/** * 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 parse($output) { $trlElements = array(); $fileCount = iterator_count($this->_fileFinder); $output->writeln('Twig-Files:'); $progress = new ProgressBar($output, $fileCount); $twig = $this->_createKwfTwigEnvironment(); foreach ($this->_fileFinder as $file) { $nodes = $twig->parse($twig->tokenize(file_get_contents($file->getRealpath()), $file->getRealpath())); $trlElementsFromFile = array(); //Recursively loop through the AST foreach ($nodes as $child) { if ($child instanceof \Twig_Node) { $trlElementsFromFile = $this->_process($child, $trlElementsFromFile); } } foreach ($trlElementsFromFile as $trlElement) { $trlElement['file'] = $file->getRealpath(); $trlElements[] = $trlElement; } $progress->advance(); } $progress->finish(); $output->writeln(''); return $trlElements; }
/** * {@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(); }
/** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $fileIterator = new File_Iterator_Facade(); $files = $input->getArgument('target'); $files = $fileIterator->getFilesAsArray($files, '.php'); $extractor = new Extractor(); $results = []; $progress = new ProgressBar($output, count($files)); foreach ($files as $file) { $results[$file] = $extractor->file($file); $progress->advance(); } $progress->clear(); $namespaces = []; foreach ($results as $file => $result) { foreach ($result as $dependency) { $namespaces[$dependency][] = $file; } } ksort($namespaces); $output->writeln(''); // line break (due to the progress bar not completely clearing out) if ($input->getOption('why')) { foreach ($namespaces as $namespace => $files) { $output->writeln($namespace); foreach ($files as $file) { $output->writeln("\t" . $file); } } } else { foreach (array_keys($namespaces) as $namespace) { $output->writeln($namespace); } } }
/** * {@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(); }
/** * Método que ejecuta el comando. * * @param InputInterface $input * @param OutputInterface $output * * @return String con los nombres de los usuarios que han sido eliminados */ protected function execute(InputInterface $input, OutputInterface $output) { //se utiliza el manager de Symfony $em = $this->getContainer()->get('doctrine.orm.entity_manager'); //se utiliza el manager de FOS $um = $this->getContainer()->get('fos_user.user_manager'); //buscar todos los usuarios $usuarios = $em->getRepository('UserBundle:Usuario')->findAll(); $UsuariosEliminados = ' '; $cantidadUsuarios = count($usuarios); //contador todos los usuarios a evaluar //Mostrar Progreso de todos los usuarios evaluados $progress = new ProgressBar($output, $cantidadUsuarios); $progress->start(); foreach ($usuarios as $usuario) { //si no ha sido confirmado esta variable es NULL if (is_null($usuario->getLastLogin())) { $um->deleteUser($usuario); //eliminar Usuario $UsuariosEliminados = $UsuariosEliminados . ' ' . $usuario->getUsername() . '\\n'; } $progress->advance(); } //terminar barra de progreso $progress->finish(); $output->writeln($UsuariosEliminados); }
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); }
public function finish() { if ($this->progressBar !== null) { $this->progressBar->finish(); $this->output->writeln(''); } }
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); }
public function fire() { if (!$this->option('verbose')) { $this->output = new NullOutput(); } $this->call('search:clear'); /** @var Search $search */ $search = App::make('search'); $modelRepositories = $search->config()->repositories(); if (count($modelRepositories) > 0) { foreach ($modelRepositories as $modelRepository) { $this->info('Creating index for model: "' . get_class($modelRepository) . '"'); $count = $modelRepository->count(); if ($count === 0) { $this->comment(' No available models found. '); continue; } $progress = new ProgressBar($this->getOutput(), $count); $progress->start(); $modelRepository->chunk(1000, function ($chunk) use($progress, $search) { foreach ($chunk as $model) { $search->update($model); $progress->advance(); } }); $progress->finish(); } $this->info(PHP_EOL . 'Operation is fully complete!'); } else { $this->error('No models found in config.php file..'); } }
/** * 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(''); }
protected function execute(InputInterface $input, OutputInterface $output) { $checksums = json_decode($this->fileChecksums, true); $root = __DIR__ . '/../'; $progressbar = new ProgressBar($output, count($checksums)); $errors = []; $missing = []; foreach ($checksums as $file => $checksum) { $progressbar->advance(); $absPath = Path::normalize($root . $file); if (!file_exists($absPath)) { $missing[] = $absPath; } elseif (md5(file_get_contents($absPath)) !== $checksum) { $errors[] = $absPath; } } $output->writeln("\n"); if (count($errors) > 0 || count($missing) > 0) { foreach ($missing as $path) { $output->writeln('<error>Missing file:</error> ' . $path); } foreach ($errors as $path) { $output->writeln('<error>Invalid checksum:</error> ' . $path); } $output->writeln("\nYour News installation does not " . 'match the recorded files and versions. This ' . 'is either caused by missing or old files or an ' . 'invalid or out of date appinfo/checksum.json ' . 'file.'); $output->writeln('Either way, please make sure that the contents ' . 'of the News app\'s directory match the ' . 'contents of the installed tarball.'); return 1; } else { $output->writeln('<info>Installation verified, everything OK!' . '</info>'); } }
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); }
public function parseCodeDirectory($output) { $this->_errors = array(); $trlElements = array(); $fileCount = iterator_count($this->_fileFinder); $output->writeln('PHP-Files:'); $progress = new ProgressBar($output, $fileCount); foreach ($this->_fileFinder as $file) { if (in_array($file, $this->_ignoredFiles)) { continue; } $progress->advance(); $this->_codeContent = $this->_replaceShortOpenTags($file->getContents()); try { foreach ($this->parseContent() as $trlElementOfFile) { $trlElementOfFile['file'] = $file->getRealpath(); $trlElements[] = $trlElementOfFile; } } catch (\PhpParser\Error $e) { $this->_errors[] = array('error' => $e, 'file' => $file->getRealPath()); } } $progress->finish(); $output->writeln(''); return $trlElements; }
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.'); }
/** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $lang = $input->getArgument(self::LANGUAGE_ARGUMENT); /** @var Language $language */ if (($language = $this->findLanguage($lang)) === NULL) { $output->writeln("<error>Unknown language {$lang} given!"); return 1; } $output->writeln('<comment>Finding scenarios...</comment>'); $scenarios = $this->scenariosRepository->fetch(new ScreenplayExportQuery($language)); $count = $scenarios->getTotalCount(); $output->writeln("<comment>Found {$count} scenarios</comment>"); $progressBar = new ProgressBar($output); $progressBar->start($count); for ($i = 0; $i <= $count; $i += self::BATCH_SIZE) { $scenarios->applyPaging($i, self::BATCH_SIZE); $scenariosArray = []; /** @var Screenplay $screenplay */ foreach ($scenarios as $screenplay) { $scenariosArray[] = $screenplay; $progressBar->advance(); } $this->screenplayProducer->publish($scenariosArray); } $progressBar->finish(); $output->writeln(""); $output->writeln("<info>Finish</info>"); }
/** * {@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); $progress->start(); $trustedServers = $this->dbHandler->getAllServer(); foreach ($trustedServers as $trustedServer) { $progress->advance(); $url = $trustedServer['url']; $sharedSecret = $trustedServer['shared_secret']; $syncToken = $trustedServer['sync_token']; if (is_null($sharedSecret)) { continue; } $targetBookId = sha1($url); $targetPrincipal = "principals/system/system"; $targetBookProperties = ['{DAV:}displayname' => $url]; try { $newToken = $this->syncService->syncRemoteAddressBook($url, 'system', $sharedSecret, $syncToken, $targetPrincipal, $targetBookId, $targetBookProperties); if ($newToken !== $syncToken) { $this->dbHandler->setServerStatus($url, TrustedServers::STATUS_OK, $newToken); } } catch (\Exception $ex) { $output->writeln("Error while syncing {$url} : " . $ex->getMessage()); } } $progress->finish(); $output->writeln(''); }
/** * @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)); } } }
/** * Exports es index to provided file. * * @param Manager $manager * @param string $filename * @param array $types * @param int $chunkSize * @param OutputInterface $output */ public function exportIndex(Manager $manager, $filename, $types, $chunkSize, OutputInterface $output) { $typesMapping = $manager->getMetadataCollector()->getMappings($manager->getConfig()['mappings']); $typesToExport = []; if ($types) { foreach ($types as $type) { if (!array_key_exists($type, $typesMapping)) { throw new \InvalidArgumentException(sprintf('Type "%s" does not exist.', $type)); } $typesToExport[] = $typesMapping[$type]['bundle'] . ':' . $typesMapping[$type]['class']; } } else { foreach ($typesMapping as $type => $typeConfig) { $typesToExport[] = $typeConfig['bundle'] . ':' . $typeConfig['class']; } } $repo = $manager->getRepository($typesToExport); $results = $this->getResults($repo, $chunkSize); $progress = new ProgressBar($output, $results->count()); $progress->setRedrawFrequency(100); $progress->start(); $metadata = ['count' => $results->count(), 'date' => date(\DateTime::ISO8601)]; $writer = $this->getWriter($this->getFilePath($filename), $metadata); foreach ($results as $data) { $doc = array_intersect_key($data, array_flip(['_id', '_type', '_source', 'fields'])); $writer->push($doc); $progress->advance(); } $writer->finalize(); $progress->finish(); $output->writeln(''); }
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..'); } }
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(); }
/** * @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(); }
function it_finishes_progress(OutputInterface $output, ProgressBar $progressBar, RunnerEvent $event) { $progressBar->setOverwrite(false)->shouldBeCalled(); $progressBar->finish()->shouldBeCalled(); $output->writeln('')->shouldBeCalled(); $this->finishProgress($event); }