PHP code example of joetjen / abstractcli

1. Go to this page and download the library: Download joetjen/abstractcli library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joetjen / abstractcli example snippets




Oetjen\AbstractCLI\AbstractCLI;
use JOetjen\AbstractCLI\CLIException;

class GreetCli extends AbstractCLI
{
    public function __construct()
    {
        parent::__construct();

        $this->setVersion('1.0.0');
        $this->setSummary('Greets someone, optionally more than once.');
        $this->setFooter('Example: greet --shout --times 3 World');

        $this->addOption(array(
            'short' => 's',
            'long'  => 'shout',
            'type'  => self::TYPE__SWITCH,
            'desc'  => 'Print the greeting in capital letters.',
        ));

        $this->addOption(array(
            'short' => 't',
            'long'  => 'times',
            'type'  => self::TYPE__OPTIONAL,
            'name'  => 'times',
            'desc'  => 'How many times to greet (default: 1).',
            'check' => 'checkTimes',
        ));

        $this->addArgument(array(
            'name' => 'NAME',
            'type' => self::TYPE__MANDATORY,
        ));
    }

    public function checkTimes($value)
    {
        if (!ctype_digit((string) $value)) {
            throw new CLIException('"%s" is not a valid number of times!', $value);
        }
    }

    protected function execute()
    {
        $name    = $this->getArgument(0); // the first argument defined, i.e. NAME
        $times   = (int) $this->getOption('times', 1);
        $message = sprintf('Hello, %s!', $name);

        if ($this->is('shout')) {
            $message = strtoupper($message);
        }

        for ($i = 0; $i < $times; $i++) {
            echo $message, PHP_EOL;
        }

        return 0;
    }
}

exit((int) GreetCli::run($argv));