PHP code example of silassare / kli

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

    

silassare / kli example snippets


#!/usr/bin/env php


Args;

$kli = Kli::new('my-tool');

$cmd = $kli->command('greet')->description('Greeting utilities');
$act = $cmd->action('say')->description('Print a greeting');
$act->option('name', 'n')->string()->def('World');
$act->handler(function (KliArgs $args) use ($kli): void {
    $kli->success('Hello, ' . $args->get('name') . '!');
});

$kli->execute($argv);

$kli = Kli::new('my-tool');

// Create a command (must be 2+ chars: [a-zA-Z0-9][a-zA-Z0-9-_]+)
$cmd = $kli->command('user');
$cmd->description('User management commands');

// Create actions on the command (colons allowed: "create:admin")
$list   = $cmd->action('list',   'List all users');
$create = $cmd->action('create', 'Create a new user');
$delete = $cmd->action('delete', 'Delete a user');

$act->option('name',  'n')            // KliOption
    ->string()                        // returns KliTypeString
    ->min(2)->max(50)
    ->def('World');

$act->option('count', 'c')
    ->number()                        // returns KliTypeNumber
    ->integer()->min(1)->def(10);

$opt->string(?int $min = null, ?int $max = null): KliTypeString

$opt->number(?float $min = null, ?float $max = null): KliTypeNumber

$opt->bool(bool $strict = false, ?string $msg = null): KliTypeBool

$opt->path(?int $min = null, ?int $max = null): KliTypePath

// Per-action handler (checked first):
$act->handler(function (KliArgs $args) use ($kli): void {
    // handle the action
});

// Command-level fallback handler (all actions that have no own handler):
$cmd->handler(function (KliAction $action, KliArgs $args) use ($kli): void {
    // $action tells you which sub-command was invoked
});

$act->option('output', 'o')->string()->def('/tmp');
$act->option('verbose')->bool()->def(false);

$act->handler(function (KliArgs $args): void {
    $path    = $args->get('output');   // by name
    $path    = $args->get('o');        // by flag
    $verbose = $args->get('verbose');  // bool
    $extra   = $args->getAnonymousArgs(); // anything after --
    $first   = $args->getAnonymousAt(0);
});

// Single position: the first bare token becomes --file
$act->option('file', 'f')->path()->offsets(0);

// Range: tokens at positions 0..2 are collected into an array
$act->option('files', 'f')->path()->multiple()->offsets(0, 2);

// Infinite range: all tokens from position 1 onward
$act->option('args')->string()->offsets(1, INF);

$act->option('password', 'p')
    ->string()->min(8)
    -> arg = hide input

$act->option('name', 'n')
    ->string()
    ->

$kli = Kli::new('my-tool', allow_interactive_mode: true);
// ... register commands/actions ...
$kli->execute($argv);

$s = $kli->style();   // fresh KliStyle instance

echo $s->bold()->apply('Important');
echo $s->red()->bold()->apply('Error text');
echo $s->green()->apply('OK');
echo $s->cyan()->dim()->apply('Hint');
echo $s->backgroundBlue()->white()->apply(' banner ');

KliStyle::forceAnsi(true);   // always emit (e.g. for tests that assert ANSI output)
KliStyle::disableAnsi(true); // never emit  (takes precedence over forceAnsi)
KliStyle::forceAnsi(false);  // restore auto-detect
KliStyle::disableAnsi(false);

$table = $kli->table();

$table->addHeader('ID',     'id')->alignRight()->setWidth(4);
$table->addHeader('Name',   'name')->alignLeft();
$table->addHeader('Active', 'active')->alignCenter()
      ->setCellFormatter(KliTableFormatter::bool());
$table->addHeader('Score',  'score')->alignRight()
      ->setCellFormatter(KliTableFormatter::number(2));

$table->addRows([
    ['id' => 1, 'name' => 'Alice', 'active' => true,  'score' => 99.5],
    ['id' => 2, 'name' => 'Bob',   'active' => false, 'score' => 74.0],
]);

echo $table;  // __toString() calls render()

class RedNegativeFormatter implements KliTableCellFormatterInterface
{
    public function format(mixed $value, KliTableHeader $header, array $row): string
    {
        return (string) $value;
    }

    public function getStyle(mixed $value, KliTableHeader $header, array $row): ?KliStyle
    {
        return $value < 0 ? (new KliStyle())->red() : null;
    }
}

$table->borderStyle()->cyan();  // color all border characters

// Override specific border characters (merges into defaults):
$table->setBorderChars(['top-left' => '+', 'top' => '-']);

$kli->info('Hint: use --help');                //   ℹ  ...  (cyan icon)
$kli->warn('Deprecated flag used');            //   ⚠  ...  (yellow icon)
$kli->success('All done');                     //   ✔  ...  (green icon)
$kli->error('Something went wrong');           //   ✖  ...  (red bold icon)
$kli->writeLn('raw output');                   // new line then string
$kli->write('inline output');
$kli->log('info', 'message');                  // append to log file (if configured)
$kli->log('error', 'oops', ['key' => 'val']); // with context
$kli->bell(1);                                 // terminal bell character

$kli->error('Fatal: cannot continue', exit: null); // just print
$kli->terminate(1);                                // always exits

class MyTool extends Kli
{
    public function getVersion(bool $full = false): string
    {
        $version = '2.3.1';
        return $full ? basename($this->getCliEntryPoint()) . ' v' . $version : $version;
    }
}

class MyApp extends Kli
{
    // Custom version string
    public function getVersion(bool $full = false): string { ... }

    // Custom welcome banner shown in interactive mode and on --help
    public function welcome(): void
    {
        $this->writeLn($this->style()->bold()->apply('Welcome to MyApp!'));
    }

    // Override input source (useful in tests)
    public function readLine(string $prompt, bool $is_password = false): string { ... }

    // Tell whether readLine() can prompt the user (default: interactive mode or STDIN is a TTY)
    public function canPrompt(): bool { ... }

    // Tell whether the last readLine() call reached the end of input
    public function isEndOfInput(): bool { ... }

    // Override terminate() to intercept exit() calls (useful in tests)
    public function terminate(int $code = 0): never
    {
        throw new MyAppExitException($code);
    }
}

$kli = new ScriptedKli('test', script: ['Alice', 'quit'], allow_interactive_mode: true);
$kli->executeString('greet say');
$this->assertSame(['Enter name: ', 'test> '], $kli->promptLog);