PHP code example of asika / simple-console

1. Go to this page and download the library: Download asika/simple-console 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/ */

    

asika / simple-console example snippets


#!/bin/sh php

// Include single file
 '/vendor/autolod.php';

$app = new \Asika\SimpleConsole\Console();

$app->execute(
    $argv,
    function () use ($app) {
        $this->writeln('Hello');
        
        // OR
        
        $app->writeln('Hello');
    
        return $app::SUCCESS; // OR `0` as success
    }
);

$app->execute(
    $argv,
    function (Console $app) {
        $app->writeln('Hello');
    
        // ...
    }
);

$app->execute(
    main: function (Console $app) {
        $app->writeln('Hello');
    
        // ...
    }
);

$app = new class () extends \Asika\SimpleConsole\Console
{
    protected function doExecute(): int|bool
    {
        $this->writeln('Hello');

        return static::SUCCESS;
    }
}

$app->execute();

// OR

$app->execute($argv);

retrun $app::SUCCESS; // 0
retrun $app::FAILURE; // 255

use Asika\SimpleConsole\Console;

function main(array $options) {
    // Run your code...
}

$parser = \Asika\SimpleConsole\Console::createArgvParser();

// Arguments
$parser->addParameter('name', type: Console::STRING, description: 'Your name', ->addParameter('--location|-l', type: Console::STRING, description: 'Live location', 

use Asika\SimpleConsole\ArgvParser;
use Asika\SimpleConsole\Console;

$params = Console::parseArgv(
    function (ArgvParser $parser) {
        // Arguments
        $parser->addParameter('name', type: Console::STRING, description: 'Your name', , empty
);

main($params);

// me.php

$app = new Console();
// Arguments
$app->addParameter('name', type: $app::STRING, description: 'Your name', as option
$app->addParameter('--height', type: $app::FLOAT, description: 'Your height', v: $argv,
    main: function () use ($app) {
        $app->writeln('Hello');
        $app->writeln('Name: ' . $app->get('name'));
        $app->writeln('Age: ' . $app->get('age'));
        $app->writeln('Height: ' . $app->get('height'));
        $app->writeln('Location: ' . $app->get('location'));
        $app->writeln('Muted: ' . $app->get('muted') ? 'Y' : 'N');

        return $app::SUCCESS;
    }
);

// me.php

$app = new class () extends Console
{
    protected function configure(): void
    {
        // Arguments
        $this->addParameter('name', type: $this::STRING, description: 'Your name', FLOAT, description: 'Your height', on doExecute(): int|bool
    {
        $this->writeln('Hello');
        $this->writeln('Name: ' . $this->get('name'));
        $this->writeln('Age: ' . $this->get('age'));
        $this->writeln('Height: ' . $this->get('height'));
        $this->writeln('Location: ' . $this->get('location'));
        $this->writeln('Muted: ' . ($this->get('muted') ? 'Y' : 'N'));

        return $this::SUCCESS;
    }
};
$app->execute();

// Use constructor
$app = new \Asika\SimpleConsole\Console(
    heading: <<<HEADER
    [Console] SHOW ME - v1.0
    
    This command can show personal information.
    HEADER,
    epilog: <<<EPILOG
    $ show-me.php John 18 
    $ show-me.php John 18 --location=Europe --height 1.75 
    
    ...more please see https://show-me.example
    EPILOG,
    commandName: 'show-me.php'
);

// Or set properties

$app->heading = <<<HEADER
[Console] SHOW ME - v1.0

This command can show personal information.
HEADER;

$app->commandName = 'show-me.php'; // If not provided, will auto use script file name
$app->epilog = <<<EPILOG
$ show-me.php John 18 
$ show-me.php John 18 --location=Europe --height 1.75 

...more please see https://show-me.example
EPILOG;

$app->execute();

$app = new class () extends Console
{
    public function showHelp(): void
    {
        $this->writeln(
            <<<HELP
            My script v1.0
            
            Options:
            -h, --help      Show this help message
            -q, --quiet     Suppress output
            -l, --location  Your location
            HELP
        );
    }

// Function style
$app->addParameter('name', type: $app::STRING, description: 'Your name', name')
    ->

$app->addParameter('--foo', type: $app::STRING, description: 'Foo description');
$app->addParameter('--muted|-m', type: $app::BOOLEAN, description: 'Muted description');

$name = $app->get('name'); // String
$height = $app->get('height'); // Int
$muted = $app->get('muted'); // Bool

$name = $app['name'];
$height = $app['height'];

if (($dir = $app['dir']) !== false) {
    $dir ??= '/path/to/default';
}

$app->addParameter('name', $app::STRING);
$app->addParameter('tag', $app::ARRAY);

// Run: console.php foo a b c d e

$app->get('tag'); // [a, b, c ,d, e]

$app->addParameter('--tag|-t', $app::ARRAY);

$app->get('tag'); // [a, b, c]

$parser->addParameter('--verbosity|-v', type: $app::LEVEL, description: 'The verbosity level of the output');

    $app->addParameter('--muted|-m', $app::BOOLEAN, default: true, negatable: true);
    

if ($app->get('age') < 18) {
    throw new \Asika\SimpleConsole\InvalidParameterException('Age must greater than 18.');
}

$app->verbosity = 3;

if ($app->verbosity > 2) {
    $app->writeln($debugInfo);
}

$app = new \Asika\SimpleConsole\Console();
// add parameters...
$app->execute(); // You can use built-in `-h` and `-v` options

$parser->addParameter(
    '--help|-h',
    static::BOOLEAN,
    'Show description of all parameters',
    default: false
);

$parser->addParameter(
    '--verbosity|-v',
    static::LEVEL,
    'The verbosity level of the output',
);

// Add other parameters...

/** @var \Asika\SimpleConsole\ArgvParser $parser */
$params = $parser->parse($argv, validate: false);

if ($params['help'] !== false) {
    echo \Asika\SimpleConsole\ParameterDescriptor::describe($parser, 'command.php');
    exit(0);
}

// Now we can validate and cast params
$params = $parser->validateAndCastParams($params);

main($params);

$app = new \Asika\SimpleConsole\Console();
$app->disableDefaultParameters = true;

// Add it manually
$app->addParameter('--help|-h', $app::BOOLEAN, default: false);

// Set verbosity
$app->verbosity = (int) env('DEBUG_LEVEL');

$app->execute(
    main: function (\Asika\SimpleConsole\Console $app) {
        if ($app->get('help')) {
            $this->showHelp();
            return 0;
        }
        
        // ...
    }
);

new Console(
    stdout: STDOUT,
    stderr: STDERR,
    stdin: STDIN
);

$fp = fopen('php://memory', 'r+');

$app = new Console(stdout: $fp);
$app->execute();

rewind($fp);
echo stream_get_contents($fp);

// This will wait user enter text...
$app->write('Please enter something: ');
$ans = $app->in();

$ans = $app->ask('What is your name: ', [$default]);

$ans = $app->askConfirm('Are you sure you want to do this? [y/N]: '); // Return BOOL

// Set default as Yes
$ans = $app->askConfirm('Are you sure you want to do this? [Y/n]: ', 'y');

$app->boolMapping[0] = [...]; // Falsy values
$app->boolMapping[1] = [...]; // Truly values

$app->exec('ls');
$app->exec('git status');
$app->exec('git commit ...');
$result = $app->exec('git push');

// All output will instantly print to STDOUT

if ($result->code !== 0) {
    // Failure
}

$result->code; // 0 is success
$result->success; // BOOL

try {
    $this->mustExec('...');
} catch (\RuntimeException $e) {
    // 
}

$app->exec('cmd...', showCmd: false);

$log = '';

$app->exec(
    'cmd ...',
    output: function (string $data, bool $err) use ($app, &$log) {
        $app->write($data, $err);
        
        $log .= $data;
    }
);

$result = $app->exec('cmd ...', output: false);

$result->output; // StdOutput of sub-process
$result->errOutput; // StdErr Output of sub-process


// Below will not write to the result object
$result = $app->exec('cmd ...');
// OR
$result = $app->exec('cmd ...', output: function () { ... });

$result->output; // Empty
$result->errOutput; // Empty

public function exec(string $cmd, \Closure|null $output = null, bool $showCmd = true): ExecResult
{
    !$showCmd || $this->writeln('>> ' . $cmd);
    
    $returnLine = system($cmd, $code);

    return new \Asika\SimpleConsole\ExecResult($code, $returnLine, $returnLine);
}

$app = new class () extends Console
{
    protected function configure(): void
    {
        $this->addParameter('task', type: $this::STRING, description: 'Task (configure|build|make|move|clear)',    $this->addParameter('--all', type: $this::STRING);
    }

    protected function doExecute(): int|bool
    {
        $params = [];

        foreach ($this->params as $k => $v) {
            // Use any camel case convert library
            $params[Str::toCamelCase($k)] = $v;
        }

        return $this->{$this['task']}(...$params);
    }

    // `...$args` is 
bash
php me.php --name="John Doe " --age=18 --height=1.8 --location=America --muted
bash
php me.php --help
bash
php console.php # `dir` is FALSE
php console.php --dir # `dir` is NULL
php console.php --dir /path/to/dir # `dir` is `/path/to/dir`
bash
php listen.php --timeout 500 --wait 100 -- php flower.php hello --name=sakura --location Japan --muted

// The last argument values will be:
// ['php', 'flower.php', 'hello', '--name=sakura', '--location', 'Japan', '--muted']
bash
php console.php # verbosity: 0
php console.php -v # verbosity: 1
php console.php -vv # verbosity: 2
php console.php -vvv # verbosity: 3