AbstractCommander::optionHelp

Option help method, write commander help.

@return void
@throws \ReflectionException
555945
final public function optionHelp()
    {
        // Show Usage
        output()->write(
            (new Format())
                ->setContextualClass(Format::INFO)
                ->setString(language()->getLine('CLI_USAGE') . ':')
                ->setNewLinesBefore(1)
                ->setNewLinesAfter(1)
        );

        // Show Actions
        $this->loadActions();

        if (count($this->actionsPool)) {
            output()->write(
                (new Format())
                    ->setContextualClass(Format::INFO)
                    ->setString($this->commandName . '/action --option=value')
            );

            output()->write(
                (new Format())
                    ->setString(language()->getLine('CLI_ACTIONS') . ':')
                    ->setNewLinesBefore(2)
                    ->setNewLinesAfter(1)
            );

            $table = new Table();
            $table->isShowBorder = false;

            foreach ($this->actionsPool as $action) {

                if ($action instanceof AbstractCommander) {
                    $table
                        ->addRow()
                        ->addColumn($action->getCommandName())
                        ->addColumn(language()->getLine($action->getCommandDescription()));
                }
            }

            output()->write(
                (new Format())
                    ->setString($table->render())
            );
        } else {
            output()->write(
                (new Format())
                    ->setContextualClass(Format::INFO)
                    ->setString($this->commandName . ' --option=value')
            );
        }

        // Show Options
        output()->write(
            (new Format())
                ->setString(language()->getLine('CLI_OPTIONS') . ':')
                ->setNewLinesBefore(2)
                ->setNewLinesAfter(1)
        );

        $table = new Table();
        $table->isShowBorder = false;

        foreach ($this->commandOptions as $optionCaller => $optionProps) {
            $table
                ->addRow()
                ->addColumn('--' . $optionCaller)
                ->addColumn($optionProps[ 'shortcut' ])
                ->addColumn(language()->getLine($optionProps[ 'description' ]));
        }

        output()->write(
            (new Format())
                ->setString($table->render())
                ->setNewLinesAfter(2)
        );

        exit(EXIT_SUCCESS);
    }
538631
public function showHelpInfo(string $command = ''): void
    {
        /** @var \Inhere\Console\IO\Input $in */
        $in = $this->input;

        // display help for a special command
        if ($command) {
            $in->setCommand($command);
            $in->setSOpt('h', true);
            $in->clearArgs();
            $this->dispatch($command);
            return;
        }

        $sep    = $this->delimiter;
        $script = $in->getScript();

        /** @var \Inhere\Console\IO\Output $out */
        $out = $this->output;
        $out->helpPanel([
            'usage'   => "$script <info>{command}</info> [--opt -v -h ...] [arg0 arg1 arg2=value2 ...]",
            'example' => [
                "$script test (run a independent command)",
                "$script home{$sep}index (run a command of the group)",
                "$script help {command} (see a command help information)",
                "$script home{$sep}index -h (see a command help of the group)",
                "$script --auto-completion --shell-env [zsh|bash] [--gen-file stdout]",
            ]
        ]);
    }
1245609
public function helpCommand(string $commandIdentifier = null)
    {
        $exceedingArguments = $this->request->getExceedingArguments();
        if (count($exceedingArguments) > 0 && $commandIdentifier === null) {
            $commandIdentifier = $exceedingArguments[0];
        }

        if ($commandIdentifier === null) {
            $this->displayHelpIndex();
        } else {
            $matchingCommands = $this->commandManager->getCommandsByIdentifier($commandIdentifier);
            $numberOfMatchingCommands = count($matchingCommands);
            if ($numberOfMatchingCommands === 0) {
                $this->outputLine('<error>No command could be found that matches the command identifier "%s".</error>', [$commandIdentifier]);
                $this->quit(1);
            } elseif ($numberOfMatchingCommands > 1) {
                $this->outputLine('<error>%d commands match the command identifier "%s":</error>', [$numberOfMatchingCommands, $commandIdentifier]);
                $this->displayShortHelpForCommands($matchingCommands);
                $this->quit(1);
            } else {
                $this->displayHelpForCommand(array_shift($matchingCommands));
            }
        }
    }
212257
public function helpAction()
    {
        $args = $this->getRequest()->getArgv();
        $command = !empty($args[2]) ? $args[2] : 'help';

        return $this->help($command);
    }
22054
public function displayHelp() {
        $string = 'Using: ' . $this->script . ' ' . $this->command . ' ';
        $where = array();
        foreach ($this->parameters as $Option) {
            /** @var $Option Option */
            $short = $Option->getShort();
            $long = $Option->getLong();
            $temp = '-' . $short . '|--' . $long;
            if (!$Option->isRequired()) {
                $string .= '[' . $temp . '] ';
            } else {
                $string .= $temp . ' ';
            }

            $where[] = '-' . $short . ', --' . $long . '  - ' . $Option->getDescription();
        }
        $string .= "\n";
        $string .= implode("\n", $where) . "\n";
        echo $string;
        exit(0);
    }
428570
public function run()
    {
        $command = new \ReflectionClass($this);
        $options = input()->get();

        if (empty($options)) {
            if ($this->welcomeNote instanceof Format or $this->welcomeNote instanceof Text) {
                output()->write($this->welcomeNote);
            } elseif (is_string($this->welcomeNote) and $this->welcomeNote !== '') {
                output()->write(
                    (new Format())
                        ->setString(language()->getLine($this->welcomeNote))
                        ->setNewLinesAfter(1)
                );
            }

            output()->write(
                (new Format())
                    ->setString($this->name . ' v' . $this->version)
                    ->setNewLinesBefore(2)
                    ->setNewLinesAfter(1)
            );

            // Run help option
            $this->optionHelp();
        } else {

            foreach ($options as $method => $arguments) {

                if ($method === 'h') {
                    $method = 'help';
                } elseif ($method === 'v') {
                    $method = 'version';
                } elseif ($method === 'vv') {
                    $method = 'verbose';
                }

                $optionMethod = camelcase('option-' . $method);

                if ($command->hasMethod($optionMethod)) {

                    $commandMethod = $command->getMethod($optionMethod);

                    if ($commandMethod->getNumberOfRequiredParameters() == 0) {
                        call_user_func([&$this, $optionMethod]);
                    } else {
                        $optionArguments = is_array($arguments)
                            ? $arguments
                            : [$arguments];

                        call_user_func_array([&$this, $optionMethod], $optionArguments);
                    }
                }
            }
        }
    }
552328
protected function findCommand(): void
    {
        if (!isset($this->args[0])) {
            return;
        }

        $newArgs = [];

        foreach ($this->args as $key => $value) {
            if ($key === 0) {
                $this->command = \trim($value);
            } elseif (\is_int($key)) {
                $newArgs[] = $value;
            } else {
                $newArgs[$key] = $value;
            }
        }

        $this->args = $newArgs;
    }
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;
    }
1064327
protected function renderActionHelp()
    {
        $action = $this->actions[$this->actionName];
        //puts name of action
        $this->appendLine($this->getColoredString($action->getDescription(), 'green'));
        $this->appendLine('');

        //puts usage hint
        $this->appendLine('Usage:');
        $this->appendLine($this->getColoredString(sprintf(
            '   %s %s [options]',
            $this->dispatcher->getParam('activeTask'),
            $this->dispatcher->getParam('activeAction')
        ), 'dark_gray'));
        $this->appendLine('');

        //puts available options
        $this->appendLine($this->getColoredString('Options:', 'gray'));
        foreach ($action->getOptions() as $option) {
            $this->appendLine($this->getColoredString(sprintf(
                '   --%s     -%s      %s',
                $option->getName(), $option->getShortName(), $option->getDescription()
            ), 'light_green'));
        }
    }
1082494
public function executeHelp($command, $option = [])
    {
        $commandClass = "\\Friday\\Console\\Command\\".ucfirst($command)."Command";
        $cmd = new $commandClass($option);
        return $cmd->help();
    }
787580
protected function configure()
    {
        $this
            ->addOption('explain', '', InputOption::VALUE_NONE, 'Explains the commands that would be executed.')
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force execution of otherwise skipped tasks.')
            ->addOption('plugin', '', InputOption::VALUE_REQUIRED, 'Load additional plugins on-the-fly')
            ->addOption('debug', '', InputOption::VALUE_NONE, "Set the debug flag")
        ;
    }
528935
public function helperAction() {
        $name = ucfirst($this->getFirstParamOrAsk('Enter application\'s name'));;
        $path = DC::getEnvironment()->getUserClassesRoot() . 'helpers/';
        FSService::makeWritable($path);
        $this->safeCreateFromTemplate($path . $name . 'Block.php', '_helper');

    }
836913
public function showOptionsForm(): void
	{
		$form = new Options\Form($this->options, $this->ADMIN_FORM_ID);
		$form->handleRequest();
		$form->write();
	}
305661
public function helpStubCommand()
    {
        $context = $this->bootstrap->getContext();
        $applicationPackage = $this->packageManager->getPackage($this->applicationPackageKey);
        $this->outputLine('<b>%s %s ("%s" context)</b>', [$this->applicationName, $applicationPackage->getInstalledVersion() ?: 'dev', $context]);
        $this->outputLine('<i>usage: %s <command identifier></i>', [$this->getFlowInvocationString()]);
        $this->outputLine();
        $this->outputLine('See "%s help" for a list of all available commands.', [$this->getFlowInvocationString()]);
        $this->outputLine();
    }
998704
public function parse($inputArgs = null) {
        $args = $this->getCommandLineArgs($inputArgs);
        if (count($args)) {
            $this->scriptName = array_shift($args);
        }

        // build help option
        $helpOpt = false;
        if ($this->helpLong) {
            $helpOpt = new Option();
            $helpOpt->long($this->helpLong);
        }
        if ($this->helpShort) {
            if (!$helpOpt) {
                $helpOpt = new Option();
            }
            $helpOpt->short($this->helpShort);
        }
        if ($helpOpt) {
            $this->configOpts[Parser::HELP_OPTION_NAME] = $helpOpt;
        }

        try {
            $parser = new Parser($this->configOpts, $this->configArgs);
            $parser->parse($args);
        }
        catch (UsageException $e) {
            if ($this->errorHandling) {
                $this->handleUsageError($e);
            }
            else {
                // re-throw exception
                throw $e;
            }
        }
        catch (ShowHelpException $e) {
            $this->showHelp();
        }

        $this->result = $parser->getResult();
    }
125019
protected static function showHelp()
    {
        \cli\line();
        \cli\out(self::$arguments->getHelpScreen(\cli\Colors::colorize('%N%n%gAvailable commands:')));
        \cli\line();
    }
703424
private function add()
    {
        $action = $this->arg->getParameter('action');

        if (!in_array($action, static::ACTION)) {
            $this->throwFailsCommand('This action is not exists', 'help add');
        }
        
        $this->command->call(
            'generate',
            $action,
            $this->arg->getParameter('target')
        );
    }