{@inheritdoc}

@throws \InvalidArgumentException
@throws \Symfony\Component\Console\Exception\CommandNotFoundException
@throws \Symfony\Component\Console\Exception\InvalidArgumentException
@throws \PhpSchool\CliMenu\Exception\InvalidTerminalException
11912
protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $builder = $this->getMenuBuilder($input, $output);
        if ($input->getOption('dump')) {
            $this->dumpCommands($builder, $output);
        } else {
            $builder->build()->open();
        }
        return 0;
    }
1328145
protected function _command() {
        $class = '\Gcs\Framework\Core\Terminal\Terminal' . ucfirst($this->_argv[0]);

        if (isset($this->_argv[1])) {
            $method = $this->_argv[1];
        }
        else if ($this->_argv[0] == 'help') {
            $method = 'help';
        }
        else {
            $method = '';
        }

        if (method_exists($class, $method)) {
            $instance = new $class($this->_argv);
            $instance->$method($this->_argv);
        }
        else {
            if (isset($this->_argv[1])) {
                echo '[ERROR] unrecognized command "' . $this->_argv[0] . ' ' . $this->_argv[1] . '"';
            }
            else {
                echo '[ERROR] unrecognized command "' . $this->_argv[0] . '"\n';
            }
        }
    }
958712
final public function handle(Command $command): void
    {
        $supportedCommandType = $this->getSupportedCommandType();
        if (!\is_a($command, $supportedCommandType)) {
            throw new InvalidCommandException(\sprintf(
                'Command must be a %s, %s given',
                $supportedCommandType,
                \get_class($command)
            ));
        }

        $this->handleCommand($command);
    }
986971
public function run( $args )
    {
        $this->command = $this->getCommand( $args );

        if ( NULL == $this->command )
        {
            throw new CommandException( 'Command: ' . $args[ 1 ] . ' not found' );
        }

        $this->processArgs( $this->command, $args );

        return $this->command->execute();
    }
86903
protected function cmdExecute() /*: void*/
    {
        /**
         * @see simplecomplex_utils_cli()
         */
        $container = Dependency::container();

        $utils = Utils::getInstance();

        // Validate input. ---------------------------------------------
        $path = $file = $path_file = '';
        if (empty($this->command->arguments['include-file'])) {
            $this->command->inputErrors[] = !isset($this->command->arguments['include-file']) ?
                'Missing \'include-file\' argument.' : 'Empty \'include-file\' argument.';
        } else {
            $include_file = $this->command->arguments['include-file'];
            $path = dirname($include_file);
            $file = basename($include_file);
            try {
                $path = $utils->resolvePath($path);
                $path_file = $path . '/' . $file;
                if (!file_exists($path_file) || !is_file($path_file)) {
                    $this->command->inputErrors[] = 'Arg include-file resolved to[' . $path_file . ']'
                        . (!file_exists($path_file) ? ' doesn\'t exist' : ' is not a file') . '.';
                }
            } catch (\Throwable $xcptn) {
                $this->command->inputErrors[] = 'Arg include-file[' . $include_file . '] is not a valid path+filename.'
                    . "\n" . $container->get('inspect')->variable($xcptn)->toString(false);
            }
        }
        $force = !empty($this->command->options['force']);
        // Pre-confirmation --yes/-y ignored for this command,
        // unless combined with --force/-f.
        // And 'silent' is neither allowed.
        if ($this->command->preConfirmed && !$force) {
            $this->command->inputErrors[] = 'Pre-confirmation \'yes\'/-y option not supported for this command,'
                . ' unless combined with \'force\'/-f option.';
        }
        if ($this->command->inputErrors) {
            foreach ($this->command->inputErrors as $msg) {
                $this->environment->echoMessage(
                    $this->environment->format($msg, 'hangingIndent'),
                    'notice'
                );
            }
            // This command's help text.
            $this->environment->echoMessage("\n" . $this->command);
            exit;
        }
        // Display command and the arg values used.---------------------
        if (!$this->command->preConfirmed || !$force) {
            $this->environment->echoMessage(
                $this->environment->format(
                    $this->environment->format($this->command->name, 'emphasize')
                    . "\n" . 'include-file (resolved): '
                    . $utils->pathReplaceDocumentRoot($path) . '/' . $this->environment->format($file, 'emphasize'),
                    'hangingIndent'
                )
            );
        }
        // Request confirmation, ignore --yes/-y pre-confirmation option;
        // ignore .risky_command_skip_confirm file placed in document root
        // ...unless combined with --force/-f option.
        if (
            (!$this->command->preConfirmed || !$force)
            && !$this->environment->confirm(
                '(RISKY) Execute that include script? Type \'yes\' to continue:',
                ['yes'],
                '',
                'Aborted executing include script.'
            )
        ) {
            exit;
        }
        // Check if the command is doable.------------------------------
        // Nothing to check here.
        try {
            // Prevent scope bleed.
            (function($pathFile) {
                include($pathFile);
            })($path_file);
            // Apparant success, at least no exception thrown.
            $this->environment->echoMessage(
                'Executed include script '
                . $utils->pathReplaceDocumentRoot($path) . '/' . $this->environment->format($file, 'emphasize'),
                'notice'
            );
        } catch (\Throwable $xcptn) {
            $this->environment->echoMessage(
                'Executing include script ' . $path . '/' . $this->environment->format($file, 'emphasize')
                . "\n" . ' produced error.',
                'warning'
            );
            /**
             * Pass on to
             * @see Bootstrap::setExceptionHandler()
             */
            throw $xcptn;
        }
        exit;
    }
289763
protected function getValidCommand()
    {
        $datetimeFormat = $this->getDatetimeFormat();
        $type           = $this->type;
        $path           = $this->path;
        $command        = $this->command;
        $debug          = $this->debug;

        $match = '(\*|[0-9]{1,2}|\*\/[0-9]{1,2}|[0-9]{1,2}\s*\-\s*[0-9]{1,2}|(([0-9]{1,2})*\s*\,\s*[0-9]{1,2})+)\s+';

        if( ! preg_match('/^'.$match.$match.$match.$match.$match.'$/', $datetimeFormat) )
        {
            throw new InvalidTimeFormatException('Services', 'crontab:timeFormatError');
        }
        else
        {
            return $datetimeFormat.
                   ( ! empty($path)    ? $path    . ' ' : '' ).
                   ( ! empty($command) ? $command . ' ' : '' ).
                   ( ! empty($type)    ? $type    . ' ' : '' ).
                   ( $debug === true   ? '>> '    . $this->crontabDir . 'debug.log 2>&1' : '' );
        }
    }
35265
public function run(Command $command, OutputFormatter $formatter = null) : Result
    {
        $cmd = $this->processor->run($command->getCommand(), $command->getAcceptableExitCodes());

        if (!$cmd->isSuccessful()) {
            throw new RuntimeException(
                'Command failed:' . PHP_EOL
                . '  exit-code: ' . $cmd->getCode() . PHP_EOL
                . '  message:   ' . $cmd->getStdErr() . PHP_EOL,
                $cmd->getCode()
            );
        }

        $formatted = $formatter !== null ? $formatter->format($cmd->getStdOutAsArray()) : [];
        $result    = new Result($cmd, $formatted);

        return $result;
    }
992472
public function aExecuteCommandTo($command) {
        $this->restartKernel();
        $kernel = $this->getKernel();

        $application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
        $application->setAutoExit(false);

        $exploded = explode(" ", $command);

        $commandsParams = [
        ];
        foreach ($exploded as $value) {
            if (!isset($commandsParams["command"])) {
                $commandsParams["command"] = $value;
            } else {
                $e2 = explode("=", $value);
//                var_dump($e2);
                if (count($e2) == 1) {
                    $commandsParams[] = $e2[0];
                } else if (count($e2) == 2) {
                    $commandsParams[$e2[0]] = $e2[1];
                }
            }
        }
        foreach ($commandsParams as $key => $value) {
            $commandsParams[$key] = $value;
        }
        $input = new \Symfony\Component\Console\Input\ArrayInput($commandsParams);
        if ($output === null) {
            $output = new \Symfony\Component\Console\Output\ConsoleOutput();
        }
        $application->run($input, $output);
//         $content = $output->fetch();
    }
1251785
public function createCommand($event) {
        if (!empty($this->commands[$event->name])) {
            if (is_callable($this->condition) && call_user_func($this->condition, $this->owner) === false) {
                return;
            }
            $class = $this->commands[$event->name];
            $command = new $class();
            if (($command instanceof CommandInterface) === false) {
                throw new InvalidParamException('Class name [' . get_class($class) . '] provided in "commands" param MUST implement the jlorente\command\base\CommandInterface interface');
            }
            $command->setReceiver($this->owner);
            CommandMapper::map($command);
        }
    }
269784
public function execute(CommandInterface $command)
    {
        $commandHandler = $this->handlerRepository->getHandler($command);

        if ($commandHandler instanceof CommandExecutorAwareInterface) {
            $commandHandler->setCommandExecutor($this);
        }

        try {
            $result = $commandHandler->handle($command);

            if (!($result instanceof CommandResultInterface)) {
                if (false === $result) {
                    $result = CommandResult::error();
                } else {
                    $result = CommandResult::success();
                }
            }
        } catch (\Exception $e) {
            if ($this->debug) {
                throw $e;
            }

            $result = CommandResult::error(null, [], $e);
        }

        $this->processMessages($command, $result);

        return $result;
    }
1113628
public function execute($command = null, array $args = array(), array $options = array())
    {
        $command = $command ?: $this->defaultCommand;
        if (!isset($this->commands[$command])) {
            throw new ConsoleException("Command '$command' does not exist");
        }
        
        $callback = $this->commands[$command];
        if (is_callable($callback)) {
            $params = array($args, $options);
            if (is_string($callback)) {
                if (strpos($callback, '::') !== false) {
                    list($classname, $methodname) = explode('::', $callback);
                    $reflection = new ReflectionMethod($classname, $methodname);
                } else {
                    $reflection = new ReflectionFunction($callback);
                }
                $params = Utils::computeFuncParams($reflection, $args, $options);
            }
            $params[] = $this;
            return call_user_func_array($callback, $params);
        }

        $method = new ReflectionMethod($callback, 'execute');
        $params = Utils::computeFuncParams($method, $args, $options);
        return $method->invokeArgs(new $callback($this), $params);
    }
286129
protected function doExecute()
    {
        $name        = $this->io->getArgument(0) ?: exit("Please enter command name");
        $namespace   = $this->io->getArgument(1) ?: exit("Please enter command namespace");
        $description = $this->getOption('d') ?: $name;

        if (!$name || !$namespace) {
            throw new \InvalidArgumentException('Need name & namespace.');
        }

        // Regularize Namespace
        $namespace = str_replace(['/', '\\'], ' ', $namespace);

        $namespace = ucwords($namespace);

        $namespace = str_replace(' ', '\\', $namespace);

        $namespace = explode('\\', $namespace);

        if ($namespace[0] == 'Command') {
            array_shift($namespace);
        }

        $class = $namespace;

        $class = array_pop($class);

        $namespace = implode('\\', $namespace);

        $replace = [
            '{{NAME}}' => $name,
            '{{NAMESPACE}}' => $namespace,
            '{{CLASS}}' => $class,
            '{{DESCRIPTION}}' => $description,
        ];

        $content = strtr($this->template, $replace);

        $config = Ioc::getConfig();

        $file = $config->get('path.root') . '/src/' . $namespace . '/' . $class . 'Command.php';

        $file = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $file);

        if (!File::write($file, $content)) {
            $this->out()->out('Failure when writing file.');

            return false;
        }

        $this->out('File generated: ' . $file);

        return true;
    }
885290
public function getCommand(string $name): AbstractCommand
	{
		if (!isset($this->commands[$name]) && !isset($this->aliases[$name]))
		{
			throw new CommandNotFoundException(sprintf('Command %s does not exist.', $name));
		}

		return $this->commands[$name] ?? $this->aliases[$name];
	}
1341010
public static function command($value): void
    {
        if (false === self::message($value)) {
            throw new Exception\InvalidCommand($value);
        }
    }
700535
protected function doExecute()
	{
		$input  = $this->getConsoleInput();
		$output = $this->getConsoleOutput();

		// If requesting the version, short circuit the application and send the version data
		if ($input->hasParameterOption(['--version', '-V'], true))
		{
			$output->writeln($this->getLongVersion());

			return 0;
		}

		$name = $this->getCommandName($input);

		// Redirect to the help command if requested
		if ($input->hasParameterOption(['--help', '-h'], true))
		{
			// If no command name was given, use the help command with a minimal input; otherwise flag the request for processing later
			if (!$name)
			{
				$name  = 'help';
				$input = new ArrayInput(['command_name' => $this->defaultCommand]);
			}
			else
			{
				$this->wantsHelp = true;
			}
		}

		// If we still do not have a command name, then the user has requested the application's default command
		if (!$name)
		{
			$name       = $this->defaultCommand;
			$definition = $this->getDefinition();

			// Overwrite the default value of the command argument with the default command name
			$definition->setArguments(
				array_merge(
					$definition->getArguments(),
					[
						'command' => new InputArgument(
							'command',
							InputArgument::OPTIONAL,
							$definition->getArgument('command')->getDescription(),
							$name
						),
					]
				)
			);
		}

		try
		{
			$this->runningCommand = null;

			$command = $this->getCommand($name);
		}
		catch (\Throwable $e)
		{
			if ($e instanceof CommandNotFoundException && !($e instanceof NamespaceNotFoundException))
			{
				(new SymfonyStyle($input, $output))->block(sprintf("\nCommand \"%s\" is not defined.\n", $name), null, 'error');
			}

			$event = new CommandErrorEvent($e, $this);

			$this->dispatchEvent(ConsoleEvents::COMMAND_ERROR, $event);

			if ($event->getExitCode() === 0)
			{
				return 0;
			}

			$e = $event->getError();

			throw $e;
		}

		$this->runningCommand = $command;
		$exitCode             = $this->runCommand($command, $input, $output);
		$this->runningCommand = null;

		return $exitCode;
	}
488074
public function command()
    {
        $cmd = func_get_args();

        if (strpos($cmd[0], 'plugin.') === 0) {
            $this->callbacks[] = $cmd;
        }
        else {
            $this->commands[] = $cmd;
        }
    }
714524
public function runCommand($command, $parameters = array(), OutputInterface $output = null)
    {
        $parameters = array_merge(
            array('command' => $command),
            $this->getDefaultParameters(),
            $parameters
        );

        $this->getApplication()->setAutoExit(false);
        $exitCode = $this->getApplication()->run(new ArrayInput($parameters), $output ?: new NullOutput());

        if (1 === $exitCode) {
            throw new \RuntimeException('This command terminated with a permission error');
        }

        if (0 !== $exitCode) {
            $this->getApplication()->setAutoExit(true);

            $errorMessage = sprintf('The command terminated with an error code: %u.', $exitCode);
            $this->output->writeln("<error>$errorMessage</error>");
            $exception = new \Exception($errorMessage, $exitCode);

            throw $exception;
        }

        return $this;
    }