@param InputInterface  $input
@param OutputInterface $output

@throws \Exception

@return ExtensionInterface[]
192202
protected function getLimitsExtensions(InputInterface $input, OutputInterface $output)
    {
        $extensions = [];

        $messageLimit = (int) $input->getOption('message-limit');
        if ($messageLimit) {
            $extensions[] = new LimitConsumedMessagesExtension($messageLimit);
        }

        $timeLimit = $input->getOption('time-limit');
        if ($timeLimit) {
            try {
                $timeLimit = new \DateTime($timeLimit);
            } catch (\Exception $e) {
                $output->writeln('<error>Invalid time limit</error>');

                throw $e;
            }

            $extensions[] = new LimitConsumptionTimeExtension($timeLimit);
        }

        $memoryLimit = (int) $input->getOption('memory-limit');
        if ($memoryLimit) {
            $extensions[] = new LimitConsumerMemoryExtension($memoryLimit);
        }

        $niceness = $input->getOption('niceness');
        if (!empty($niceness) && is_numeric($niceness)) {
            $extensions[] = new NicenessExtension((int) $niceness);
        }

        return $extensions;
    }
672296
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $dryRun = $input->getOption('dry-run');
        $skipErrors = $input->getOption('skip-errors');
        $batchSize = NumberUtils::bound($input->getOption('batch-size'), 1, 1000);
        $batchDelay = NumberUtils::bound($input->getOption('batch-delay'), 100, 600000);
        $since = $input->getOption('since');
        $until = $input->getOption('until');
        $context = json_decode($input->getOption('context') ?: '{}', true);
        $context['tenant_id'] = (string)$input->getOption('tenant-id');
        $context['skip_errors'] = $skipErrors;
        $context['reindexing'] = true;
        $streamId = $input->getArgument('stream-id') ? StreamId::fromString($input->getArgument('stream-id')) : null;

        if (!empty($since)) {
            $since = Microtime::fromString(str_pad($since, 16, '0'));
        }

        if (!empty($until)) {
            $until = Microtime::fromString(str_pad($until, 16, '0'));
        }

        $io = new SymfonyStyle($input, $output);
        $io->title(sprintf('Reindexing events from stream "%s"', $streamId ?? 'ALL'));
        if (!$this->readyForPbjxTraffic($io)) {
            return;
        }

        $this->createConsoleRequest();
        $batch = 1;
        $i = 0;
        $reindexed = 0;
        $queue = [];
        //$io->comment(sprintf('Processing batch %d from stream "%s".', $batch, $streamId ?? 'ALL'));
        $io->comment(sprintf('context: %s', json_encode($context)));
        $io->newLine();

        $receiver = function (Event $event, StreamId $streamId) use (
            $output,
            $io,
            $context,
            $dryRun,
            $skipErrors,
            $batchSize,
            $batchDelay,
            &$batch,
            &$reindexed,
            &$i,
            &$queue
        ) {
            if (!$event instanceof Indexed) {
                $io->note(sprintf(
                    'IGNORING - Event [%s] does not have mixin [gdbots:pbjx:mixin:indexed].',
                    $event->generateMessageRef()
                ));
                return;
            }

            ++$i;
            $output->writeln(
                sprintf(
                    '<info>%d.</info> <comment>stream:</comment>%s, <comment>occurred_at:</comment>%s, ' .
                    '<comment>curie:</comment>%s, <comment>event_id:</comment>%s',
                    $i,
                    $streamId,
                    $event->get('occurred_at'),
                    $event::schema()->getCurie()->toString(),
                    $event->get('event_id')
                )
            );
            $queue[] = $event->freeze();

            if (count($queue) >= $batchSize) {
                $events = $queue;
                $queue = [];
                $this->reindex($events, $reindexed, $io, $context, $batch, $dryRun, $skipErrors);
                ++$batch;

                if ($batchDelay > 0) {
                    //$io->newLine();
                    //$io->note(sprintf('Pausing for %d milliseconds.', $batchDelay));
                    usleep($batchDelay * 1000);
                }

                //$io->comment(sprintf('Processing batch %d.', $batch));
                //$io->newLine();
            }
        };

        if ($streamId) {
            $this->getPbjx()->getEventStore()->pipeEvents($streamId, $receiver, $since, $until, $context);
        } else {
            $this->getPbjx()->getEventStore()->pipeAllEvents($receiver, $since, $until, $context);
        }

        $this->reindex($queue, $reindexed, $io, $context, $batch, $dryRun, $skipErrors);
        $io->newLine();
        $io->success(sprintf('Reindexed %s events from stream "%s".', number_format($reindexed), $streamId ?? 'ALL'));
    }
624859
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->showExecTitle($input, $output);
        $this->prepareExecute($input);

        $cliOptions = array(
            'sys_phpunit_config' => $input->getArgument('phpunit-config'),
            'sys_phpunit_config_test_suite' => $input->getOption('phpunit-config-suite'),
            'sys_stop_on_error' => $input->getOption('stop-on-error'),
            'sys_stop_on_failure' => $input->getOption('stop-on-failure'),
            'raw_scan_source' => $input->getOption('raw-scan-path'),
            'raw_scan_autoload_file' => $input->getOption('raw-autoload-file'),
            'raw_scan_exclude_path' => $input->getOption('raw-exclude-path'),
        );

        $outOptions = array(
            'out_verbose' => $input->getOption('verbose'),
            'out_format' => $input->getOption('output-format'),
            'out_level' => (int) $input->getOption('output-level'),
            'out_no_ansi' => $input->getOption('no-ansi'),
            'out_no_echo' => $input->getOption('quiet'),
        );

        try {
            $scanner = new CoverFishScanner($cliOptions, $outOptions, $output);
            $scanner->analysePHPUnitFiles();
        } catch (CoverFishFailExit $e) {
            return CoverFishFailExit::RETURN_CODE_SCAN_FAIL;
        }

        return 0;
    }
227191
private function generateOutput(InputInterface $input): OutputInterface
    {
        return new Output(
            $this->name,
            array_merge(
                $this->evaluateInputExports($input),
                $this->generateOutputParams($input)
            )
        );
    }
604821
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getApplication()->getContainer();

        $container->setParam(
            'formatter.name',
            $input->getOption('format') ?: $container->getParam('formatter.name')
        );
        $container->configure();

        $locator = $input->getArgument('spec');
        $linenum = null;
        if (preg_match('/^(.*)\:(\d+)$/', $locator, $matches)) {
            list($_, $locator, $linenum) = $matches;
        }

        $suite       = $container->get('loader.resource_loader')->load($locator, $linenum);
        $suiteRunner = $container->get('runner.suite');

        return $container->get('console.result_converter')->convert(
            $suiteRunner->run($suite)
        );
    }
145806
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->setOutput($output);
        //
        if ($this->database && config('components.database')) {
            Database::ini();
        } elseif ($this->database && !config('components.database')) {
            exception(LogicException::class, 'The database surface is disabled');
        }
        //
        $this->handle();
    }
153146
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $method = method_exists($this, 'process') ? 'process' : 'handle';

        return $this->{$method}();
    }
1342093
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $gen = new CodeGenerator(
            Database::getConnection(),
            array('default' => 'PHPCI'),
            array('default' => PHPCI_DIR),
            false
        );

        $gen->generateModels();
        $gen->generateStores();
    }
729668
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->injectOutputIntoLogger($output, $this->logger);
        $this->mountManager->setLogger($this->logger);
        $source = $input->getArgument('source');
        $destination = $input->getArgument('destination');

        $options = [
            'delete'            => $input->getOption('delete'),
            'ignore_timestamps' => $input->getOption('ignore-timestamps'),
            'excludes'          => $input->getOption('exclude'),
            'includes'          => $input->getOption('include'),
            'batch_size'        => $input->getOption('batch-size'),
        ];
        $this->mountManager->sync($source, $destination, $options);
        return 0;
    }
772518
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $error = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;

        if (!($input->getOption('php-files')
            || $input->getOption('composer')
            || $input->getOption('bower')
            || $input->getOption('packages'))
        ) {
            $error->writeln('<error>You must select at least one validation to run!</error>');
            $error->writeln('check-author.php [--php-files] [--composer] [--bower] [--packages]');

            return 1;
        }

        $this->enableDeprecatedNoProgressBar($input);

        $config = new Config();

        if (!$input->getOption('do-not-ignore-well-known-bots')) {
            $configFile = \dirname(\dirname(__DIR__))
                . DIRECTORY_SEPARATOR . 'defaults'
                . DIRECTORY_SEPARATOR . 'ignore-well-known-bots.yml';
            $config->addFromYml($configFile);
        }

        $configFile = $input->getOption('config');
        if (\is_file($configFile)) {
            $config->addFromYml($configFile);
        }

        $config
            ->ignoreAuthors($input->getOption('ignore'))
            ->excludePaths($input->getOption('exclude'))
            ->includePaths(
                \array_filter(\array_map('realpath', $input->getArgument('include')))
            );

        $paths = \array_values($config->getIncludedPaths());
        $git   = new GitRepository($this->determineGitRoot($paths[0]));
        if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
            $git->getConfig()->setLogger(
                new ConsoleLogger($output)
            );
        }

        $cacheDir = \rtrim((($tmpDir = ('\\' === PATH_SEPARATOR
            ? \getenv('HOMEDRIVE') . \getenv('HOMEPATH')
            : \getenv('HOME'))) ? $tmpDir : \sys_get_temp_dir()), '\\/');
        if ($input->getOption('cache-dir')) {
            $cacheDir = \rtrim($input->getOption('cache-dir'), '/');
        }
        $cacheDir .= '/.cache/phpcq-author-validation';

        if ($output->isVerbose()) {
            $error->writeln(\sprintf('<info>The folder "%s" is used as cache directory.</info>', $cacheDir));
        }

        $cachePool = new DoctrineCachePool(
            $input->getOption('no-cache')
                ? new VoidCache()
                : new FilesystemCache($cacheDir)
        );

        $diff         = $input->getOption('diff');
        $extractors   = $this->createSourceExtractors($input, $error, $config, $cachePool);
        $gitExtractor = $this->createGitAuthorExtractor($input->getOption('scope'), $config, $error, $cachePool, $git);
        $progressBar  = !$output->isQuiet() && !$input->getOption('no-progress') && \posix_isatty(STDOUT);
        $comparator   = new AuthorListComparator($config, $error, $progressBar);
        $comparator->shallGeneratePatches($diff);

        $failed = $this->handleExtractors($extractors, $gitExtractor, $comparator);

        if ($failed && $diff) {
            $output->writeln($comparator->getPatchSet());
        }

        return $failed ? 1 : 0;
    }
347975
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->setInputAndOutput($input, $output);

        return $this->doExecute();
    }
721841
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $templateName = $input->getArgument('template');
        $templates = $this->configurationManager->get('store.templates');
        $templateFound = array_reduce(
            $templates,
            function ($alreadyFound, $template) use ($templateName) {
                return $alreadyFound || ($template['bundle'] == $templateName);
            },
            false);

        if (!$templateFound) {
            throw new Exception(sprintf('Template %s not found', $templateName));
        }

        $this
            ->configurationManager
            ->set('store.template', $templateName);

        $formatter = $this->getHelper('formatter');
        $formattedLine = $formatter->formatSection(
            'OK',
            'Template "' . $templateName . '" enabled'
        );

        $output->writeln($formattedLine);
    }
1014081
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);

        $this->setOutput($output);
        $this->setVerbosity($output->getVerbosity());

        if ($input->getOption('child') && $output->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
            $this->setVerbosity(self::VERBOSITY_CHILD);
        }

        $this->getContainer()->get('ez_migration_bundle.step_executed_listener.tracing')->setOutput($output);

        $migrationService = $this->getMigrationService();

        $force = $input->getOption('force');

        $toExecute = $this->buildMigrationsList($input->getOption('path'), $migrationService, $force);

        if (!count($toExecute)) {
            $output->writeln('<info>No migrations to execute</info>');
            return 0;
        }

        $this->printMigrationsList($toExecute, $input, $output);

        if (!$input->getOption('child')) {
            // ask user for confirmation to make changes
            if (!$this->askForConfirmation($input, $output)) {
                return 0;
            }
        }

        if ($input->getOption('separate-process')) {
            $builder = new ProcessBuilder();
            $executableFinder = new PhpExecutableFinder();
            if (false !== $php = $executableFinder->find()) {
                $builder->setPrefix($php);
            }
            $builderArgs = $this->createChildProcessArgs($input);
        }

        // For cli scripts, this means: do not die if anyone yanks out our stdout.
        if ($input->getOption('survive-disconnected-tty')) {
            ignore_user_abort(true);
        }

        // allow forcing handling of sigchild. Useful on eg. Debian and Ubuntu
        if ($input->getOption('force-sigchild-enabled')) {
            Process::forceSigchildEnabled(true);
        }

        $aborted = false;
        $executed = 0;
        $failed = 0;
        $skipped = 0;
        $total = count($toExecute);

        /** @var MigrationDefinition $migrationDefinition */
        foreach ($toExecute as $name => $migrationDefinition) {

            // let's skip migrations that we know are invalid - user was warned and he decided to proceed anyway
            if ($migrationDefinition->status == MigrationDefinition::STATUS_INVALID) {
                $output->writeln("<comment>Skipping $name</comment>");
                $skipped++;
                continue;
            }

            $this->writeln("<info>Processing $name</info>");

            if ($input->getOption('separate-process')) {

                try {
                    $this->executeMigrationInSeparateProcess($migrationDefinition, $migrationService, $builder, $builderArgs);

                    $executed++;
                } catch (\Exception $e) {
                    $failed++;


                    $errorMessage = $e->getMessage();
                    // we probably have already echoed the error message while the subprocess was executing, avoid repeating it
                    if ($errorMessage != $this->subProcessErrorString) {
                        if ($e instanceof AfterMigrationExecutionException) {
                            $errorMessage = "Failure after migration end! Reason: " . $errorMessage;
                        } else {
                            $errorMessage = "Migration failed! Reason: " . $errorMessage;
                        }

                        $this->writeErrorln("\n<error>$errorMessage</error>");
                    }

                    if (!$input->getOption('ignore-failures')) {
                        $aborted = true;
                        break;
                    }
                }

            } else {

                try {
                    $this->executeMigrationInProcess($migrationDefinition, $force, $migrationService, $input);

                    $executed++;
                } catch (\Exception $e) {
                    $failed++;

                    $this->writeErrorln("\n<error>Migration failed! Reason: " . $e->getMessage() . "</error>");

                    if (!$input->getOption('ignore-failures')) {
                        $aborted = true;
                        break;
                    }
                }

            }
        }

        $missed = $total - $executed - $failed - $skipped;

        if ($aborted) {
            if ($missed > 0) {
                $this->writeErrorln("\n<error>Migration execution aborted</error>");
            }
        } else {
            // NB: as per the Sf doc at https://symfony.com/doc/2.7/console/calling_commands.html, the 'cache:clear'
            // command should be run 'at the end', as they change some class definitions
            if ($input->getOption('clear-cache')) {
                $command = $this->getApplication()->find('cache:clear');
                $inputArray = new ArrayInput(array('command' => 'cache:clear'));
                $command->run($inputArray, $output);
            }
        }

        $this->writeln("\nExecuted $executed migrations, failed $failed, skipped $skipped" . ($missed ? ", missed $missed" : ''));

        $time = microtime(true) - $start;
        if ($input->getOption('separate-process')) {
            // in case of using subprocesses, we can not measure max memory used
            $this->writeln("<info>Time taken: ".sprintf('%.2f', $time)." secs</info>");
        } else {
            $this->writeln("<info>Time taken: ".sprintf('%.2f', $time)." secs, memory: ".sprintf('%.2f', (memory_get_peak_usage(true) / 1000000)). ' MB</info>');
        }

        return $failed;
    }
503861
public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;
        try {
            $this->doExecute($input, $output);
        } catch (\Exception $e) {
            $this->writeException($e);
        }
    }
185737
protected function interact(InputInterface $input, OutputInterface $output)
    {
        if (!$input->getArgument('bundle')) {
            $bundle = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please give the bundle:',
                function($bundle)
                {
                    if (empty($bundle)) {
                        throw new \Exception('Bundle can not be empty');
                    }

                    return $bundle;
                }
            );
            $input->setArgument('bundle', $bundle);
        }
    }
1041447
private function getReadyAdapter(InputInterface $input, OutputInterface $output)
    {
        $adapterClass = $this->getAdapterClassFromArgument($input->getArgument('adapter'));

        try {
            $adapter = new $adapterClass();
        } catch (\Exception $e) {
            $adapterData = [];
            preg_match_all('/"(.*)"/i', $e->getMessage(), $matches);

            foreach ($matches[1] as $match) {
                $optionKey = str_replace('_', '-', Inflector::tableize($match));
                $option    = $input->getOption($optionKey);

                if (!$option) {
                    throw new AdapterException(
                        sprintf(
                            'The option "%s" is needed by %s adapter',
                            $optionKey,
                            $adapterClass
                        )
                    );
                }

                $adapterData[$match] = $option;
            }

            $adapter = new $adapterClass($adapterData);
        }

        return $adapter;
    }
13054
protected function getProgramOptions(
        InputInterface $input,
        OutputInterface $output
    ) {
        $opts = array();

        foreach ($this->getDefinition()->getOptions() as $o) {
            $name = $o->getName();
            if (! array_key_exists($name, $this->programOptions )) {
                continue;
            }
            $value = $input->getOption($name);
            if ($o->acceptValue() && $value !== null) {
                $opts[$this->programOptions[$name]] = $value;
            } else if (! $o->acceptValue() && $value === true) {
                $opts[] = $this->programOptions[$name];
            }
        }

        return array_merge(
            $opts,
            $this->getVerbosityOptions($output->getVerbosity())
        );
    }