Application Console

This section provides an introduction into console service. Console tools are ideal for use in cron jobs, or command line based utilities that don’t need to be accessible from a web browser.

Console Commands

Console command is a class defining a route and an event handler.

use WebinoAppLib\Console\AbstractConsoleCommand;

class MyConsoleCommand extends AbstractConsoleCommand
{
    public function configure(Console $console)
    {
        $console
            ->setRoute('my-command')
            ->setTitle('My command title')
            ->setDescription('My command description.');
    }

    public function handle(ConsoleEvent $event)
    {
        // obtaining console service
        $cli = $event->getCli();

        // obtaining command parameters
        $event->getParam('myCommandArgument');

        // doing something...
        $cli->out('My console command example!');
    }
}

Adding custom console command into application configuration.

use WebinoAppLib\Feature\Config;

new Config([
    new MyConsoleCommand,
]);

Console Bind

It is also possible to configure console command routes particularly.

use WebinoAppLib\Feature\Config;
use WebinoAppLib\Feature\Route\Console;

new Config([
    (new Console('my-command'))
        ->setRoute('my-command')
        ->setTitle('My command title')
        ->setDescription('My command description.'),
]);

You can attach code to any console command execution.

use WebinoAppLib\Event\ConsoleEvent;

$app->bindConsole('my-command', function (ConsoleEvent $event) {
    // obtaining console service
    $cli = $event->getCli();

    // obtaining command parameters
    $event->getParam('myCommandArgument');

    // doing something...
});

Performing action on a default console command execution.

use WebinoAppLib\Console\ConsoleDefault;
use WebinoAppLib\Event\ConsoleEvent;

$app->bindConsole(ConsoleDefault::class, function (ConsoleEvent $event) {
    // do something...
});

Command Parameters

Obtaining command parameters.

/** @var \WebinoAppLib\Event\ConsoleEvent $event */
$value = $event->getParam('myCommandArgument');

Arguments

Arguments are expected to appear on the command line exactly the way they are spelled in the route.

Providing required argument alternatives.

'my-command (requiredArgumentA|requiredArgumentB)'

Required and optional argument values.

'my-command <requiredArgumentValue> [<optionalArgumentValue>]'

Providing optional argument alternatives.

'my-command [optionalArgumentA|optionalArgumentB]'

Options

You can define any number of optional and required options. The order of options is ignored. They can be defined in any order and the user can provide them in any other order.

Providing required option alternatives.

'my-command (--requiredOptionA|--requiredOptionB)'

Optional option and its short alternative.

'my-command [--optionalOption|-o]'

Options can digest text-based values.

'my-command --requiredOptionValue= [--optionalOptionValue=]'

Console Config

Console

Configuring console command routes.

use WebinoAppLib\Application\CoreConfig;
use WebinoAppLib\Feature\Route\Console;

new CoreConfig([

    (new Console('my-basic-command'))
        ->setRoute('my-command')
        ->setTitle('My command title'),,

    (new Console('my-extra-command'))
        ->setRoute('my-command <requiredArgumentValue> --requiredOptionValue=')
        ->setTitle('My command title')
        ->setDescription([
            'My extra command',
            'multi-line description.',
        ])
        ->setArgumentsDescription([
            'requiredArgumentValue' => 'Enter custom argument value',
        ])
        ->setOptionsDescription([
            'requiredOptionValue=' => 'Enter custom option value',
        ]),
]);

Console Interface

$app->bindConsole()

Binding to console commands.

use WebinoAppLib\Event\ConsoleEvent;

$app->bindConsole('my-command', function (ConsoleEvent $event) {
    // obtaining console service
    $cli = $event->getCli();

    // obtaining command parameters
    $event->getParam('myCommandArgument');

    // doing something...
});

Console Event

$event->getCli()

Obtaining the console service from the console event object.

use WebinoAppLib\Event\ConsoleEvent;

$consoleEventHandler = function (ConsoleEvent $event) {
    $cli = $event->getCli();
};

Fluent interface:

// Method chaining
$cli->red('Red text!')->green('Green text!');

// If you prefer, you can also simply chain
// the color method and continue using out.
$cli->blue()->out('Blue? Wow!');

$event->getParam()

Accessing command arguments/options.

/** @var \WebinoAppLib\Event\ConsoleEvent $event */
$value = $event->getParam('myCommandArgument');

$cli->out()

Printing text to the terminal.

$cli->out('Console text!');

$cli->inline()

Printing text inline to the terminal, without ending line break.

$cli->inline('Inline console text!');

$cli->columns()

List out an array of data so that it is easily readable.

$data = [
    '12 Monkeys',
    '12 Years a Slave',
    'A River Runs Through It',
    'Across the Tracks',
    'Babel',
    'Being John Malkovich',
    'Burn After Reading',
    'By the Sea',
    'Confessions of a Dangerous Mind',
    'Contact',
    'Cool World',
    'Cutting Class',
    'Fight Club',
    'Fury',
    'Happy Feet Two',
    'Happy Together',
    'Hunk',
    'Inglourious Basterds',
    'Interview with the Vampire',
    'Johnny Suede',
    'Kalifornia',
    'Killing Them Softly',
    'Legends of the Fall',
    'Less Than Zero',
    'Meet Joe Black',
    'Megamind',
    'Moneyball',
];

$cli->columns($data);

Specify the number of columns by passing in a second parameter.

$cli->columns($data, 4);

Note

Console service will try to figure out how the content best fits in your terminal by default.

Specify the columns via an array of arrays.

$data = [
    ['Gary', 'Mary', 'Larry', 'Terry'],
    [1.2, 4.3, 0.1, 3.0],
    [6.6, 4.4, 5.5, 3.3],
    [9.1, 8.2, 7.3, 6.4],
];

$cli->columns($data);

$cli->table()

Make table out of an array of data so that it is easily readable.

$data = [
    [
      'Walter White',
      'Father',
      'Teacher',
    ],
    [
      'Skyler White',
      'Mother',
      'Accountant',
    ],
    [
      'Walter White Jr.',
      'Son',
      'Student',
    ],
];

$cli->table($data);

If you pass in an array of associative arrays or objects, the keys will automatically become the header of the table.

$data = [
    [
        'name'       => 'Walter White',
        'role'       => 'Father',
        'profession' => 'Teacher',
    ],
    [
        'name'       => 'Skyler White',
        'role'       => 'Mother',
        'profession' => 'Accountant',
    ],
    [
        'name'       => 'Walter White Jr.',
        'role'       => 'Son',
        'profession' => 'Student',
    ],
];

$cli->table($data);

$cli->json()

Printing pretty-printed JSON to the terminal.

$cli->json([
    'name' => 'Gary',
    'age'  => 52,
    'job'  => 'Engineer',
]);

$cli->br()

Printing line breaks to the terminal.

$cli->br();

// many at once
$cli->br(3);

// method chaining
$cli->br()->out('I have moved down a line.');

$cli->tab()

Printing tabulators to the terminal.

$cli->tab();

// many at once
$cli->tab(3);

// method chaining
$cli->tab()->out('I am all sorts of indented.');

$cli->draw()

Drawing some ASCII art.

$cli->draw('bender');

$cli->border()

Inserting borders to break up output. Outputs a dashed border by default.

$cli->border();

// character(s) to be repeated
$cli->border('*');

// length of the border
$cli->border('*', 50);

$cli->dump()

Dumping variables out to the terminal.

$cli->dump([
    'This',
    'That',
    'Other Thing',
]);

$cli->flank()

Bringing a little more attention to text.

$cli->flank('Look at me. Now.');

// specifying the flanking characters
$cli->flank('Look at me. Now.', '!');

// and how many flanking characters there should be
$cli->flank('Look at me. Now.', '!', 5);

$cli->progress()

Adding progress bars to the terminal.

$progress = $cli->progress()->total(100);
// or shorthand it and pass the total
// right into the progress method
$progress = $cli->progress(100);

for ($i = 0; $i <= 100; $i++) {
    $progress->current($i);

    // simulate something happening
    usleep(rand(10000, 300000));
}

You can also manually advance the bar.

$progress = $cli->progress(100);

// do something..

$progress->advance(); // adds 1 to the current progress

// do something..

$progress->advance(10); // adds 10 to the current progress

// do something..

$progress->advance(5, 'Still going.'); // adds 5, displays a label

Pass a label into the current method if you’d like a more descriptive indicator of where you are in the process.

$items = [
    'php',
    'javascript',
    'python',
    'ruby',
    'java',
];

$progress = $cli->progress(count($items));

foreach ($items as $key => $value) {
    $progress->current($key + 1, $value);

    // simulate something happening
    usleep(rand(10000, 300000));
}

$cli->padding()

Padding out a string to a specified length, allowing for neatly organized data.

$padding = $cli->padding(20);
// or specify the padding character(s)
$padding = $cli->padding(20, '-');

$padding->label('Eggs')->result('1.99€');
$padding->label('Oatmeal')->result('4.99€');
$padding->label('Bacon')->result('2.99€');

$cli->animation()

Taking ASCII art and running basic animations on it in the terminal. Valid directions are left, top, right and bottom.

// movement
$cli->animation('bender')->enterFrom('left');
$cli->animation('bender')->exitTo('left');

// scrolling
$cli->animation('bender')->scroll('left');

Altering the speed of the animation. The parameter should be an integer representing the percentage of the default speed.

// animate twice as fast
$cli->animation('bender')->speed(200)->scroll('left');

Note

50 would make it slower by half, whereas 200 would make it run at twice the speed.

You can create a directory of text files that represent each keyframe in an animation and just run it manually.

$cli->addArt('my/folder/custom-animation');
$cli->animation('custom-animation')->run();

Note

You can add custom ASCII art using the addArt method.

$cli->addArt()

Adding your own art by setting the directory in which it is located.

my/
  folder/
    art/
      dog.txt
      cat.txt
      mug.txt

Let the console service know where it is via the full path.

$cli->addArt('my/folder/art');

Now you can use anything in that directory.

$cli->draw('dog');
$cli->red()->draw('cat');
$cli->boldDraw('mug');

You can style your art using tags:

<blue>     ( )</blue>
<blue>      H</blue>
<blue>      H</blue>
<blue>     _H_</blue>
<blue>  .-'-.-'-.</blue>
<blue> /         \</blue>
<blue>|           |</blue>
<blue>|   .-------'._</blue>
<blue>|  /<white>/  '.' '.</white> \</blue>
<blue>|  \<white>\ <black><red>@   @</red></black> /</white> /</blue>
<blue>|   '---------'</blue>
<blue>|    _______|</blue>
<blue>|  .'<black>-+-+-+</black>|</blue>
<blue>|  '.<black>-+-+-+</black>|</blue>
<blue>|    """""" |</blue>
<blue>'-.__   __.-'</blue>
<blue>     """</blue>

$cli->clear()

Clearing the terminal.

$cli->clear();

Colors

$cli->black()

Printing text in black color to the terminal.

$cli->black('Black text!');

$cli->red()

Printing text in red color to the terminal.

$cli->red('Red text!');

$cli->green()

Printing text in green color to the terminal.

$cli->green('Green text!');

$cli->yellow()

Printing text in yellow color to the terminal.

$cli->yellow('Yellow text!');

$cli->blue()

Printing text in blue color to the terminal.

$cli->blue('Blue text!');

$cli->magenta()

Printing text in magenta color to the terminal.

$cli->magenta('Magenta text!');

$cli->cyan()

Printing text in cyan color to the terminal.

$cli->cyan('Cyan text!');

$cli->lightGray()

Printing text in light gray color to the terminal.

$cli->lightGray('Light gray text!');

$cli->darkGray()

Printing text in dark gray color to the terminal.

$cli->darkGray('Dark gray text!');

$cli->lightRed()

Printing text in light red color to the terminal.

$cli->lightRed('Light red text!');

$cli->lightGreen()

Printing text in light green color to the terminal.

$cli->lightGreen('Light green text!');

$cli->lightYellow()

Printing text in light yellow color to the terminal.

$cli->lightYellow('Light yellow text!');

$cli->lightBlue()

Printing text in light blue color to the terminal.

$cli->lightBlue('Light blue text!');

$cli->lightMagenta()

Printing text in light magenta color to the terminal.

$cli->lightMagenta('Light magenta text!');

$cli->lightCyan()

Printing text in light cyan color to the terminal.

$cli->lightCyan('Light cyan text!');

$cli->white()

Printing text in white color to the terminal.

$cli->white('White text!');

Background Colors

$cli->backgroundBlack()

Printing text on black background color to the terminal.

$cli->backgroundBlack('Text on black background!');

$cli->backgroundRed()

Printing text on red background color to the terminal.

$cli->backgroundRed('Text on red background!');

$cli->backgroundGreen()

Printing text on green background color to the terminal.

$cli->backgroundGreen('Text on green background!');

$cli->backgroundYellow()

Printing text on yellow background color to the terminal.

$cli->backgroundYellow('Text on yellow background!');

$cli->backgroundBlue()

Printing text on blue background color to the terminal.

$cli->backgroundBlue('Text on blue background!');

$cli->backgroundMagenta()

Printing text on magenta background color to the terminal.

$cli->backgroundMagenta('Text on magenta background!');

$cli->backgroundCyan()

Printing text on cyan background color to the terminal.

$cli->backgroundCyan('Text on cyan background!');

$cli->backgroundLightGray()

Printing text on light gray background color to the terminal.

$cli->backgroundLightGray('Text on light gray background!');

$cli->backgroundDarkGray()

Printing text on dark gray background color to the terminal.

$cli->backgroundDarkGray('Text on dark gray background!');

$cli->backgroundLightRed()

Printing text on light red background color to the terminal.

$cli->backgroundLightRed('Text on light red background!');

$cli->backgroundLightGreen()

Printing text on light green background color to the terminal.

$cli->backgroundLightGreen('Text on light green background!');

$cli->backgroundLightYellow()

Printing text on light yellow background color to the terminal.

$cli->backgroundLightYellow('Text on light yellow background!');

$cli->backgroundLightBlue()

Printing text on light blue background color to the terminal.

$cli->backgroundLightBlue('Text on light blue background!');

$cli->backgroundLightMagenta()

Printing text on light magenta background color to the terminal.

$cli->backgroundLightMagenta('Text on light magenta background!');

$cli->backgroundLightCyan()

Printing text on light cyan background color to the terminal.

$cli->backgroundLightCyan('Text on light cyan background!');

$cli->backgroundWhite()

Printing text on white background color to the terminal.

$cli->backgroundWhite('Text on white background!');

Text Style

$cli->bold()

Printing bold text to the terminal.

$cli->bold('Bold text!');

$cli->dim()

Printing dim text to the terminal.

$cli->dim('Dim text!');

$cli->underline()

Printing underlined text to the terminal.

$cli->underline('Underlined text!');

$cli->invert()

Printing inverted text to the terminal.

$cli->invert('Inverted text!');

Style Commands

$cli->info()

Printing text in an info style to the terminal.

$cli->info('Info text style!');

$cli->comment()

Printing text in a comment style to the terminal.

$cli->comment('Comment text style!');

$cli->whisper()

Printing text in a whisper style to the terminal.

$cli->whisper('Whisper text style!');

$cli->shout()

Printing text in a shout style to the terminal.

$cli->shout('Shout text style!');

$cli->error()

Printing text in an error style to the terminal.

$cli->error('Error text style!');

User Input

$cli->input()

Getting text from a user.

// basic input
$input  = $cli->input('How you doin?');
$result = $input->prompt();

// multi-line input
$input  = $cli->input('>>>')->multiLine();
$result = $input->prompt();

Note

Multi-line input will wait for CTRL+D before returning.

Specifying certain answers from the user you only want to accept (case insensitive).

$input  = $cli->input('How you doin?')->accept(['Fine', 'Ok']);
$result = $input->prompt();

// or showing expecting answers
$input  = $cli->input('How you doin?')->accept(['Fine', 'Ok'], true);
$result = $input->prompt();

Note

User will be re-prompted until responds with an acceptable answer.

Expecting answers exactly as they are specified (case sensitive).

$input  = $cli->input('How you doin?')->accept(['Fine', 'Ok'])->strict();
$result = $input->prompt();

Note

Answering fine or ok will cause a re-prompt.

Passing a closure into the accept method.

$input = $cli->input('How you doin?');

$input->accept(function($result) {
    return ('Fine' === $result);
});

$result = $input->prompt();

Specifying a default response for when the user simply presses enter without typing anything in.

$input  = $cli->input('How you doin?')->defaultTo('Great!');
$result = $input->prompt();

$cli->confirm()

Prompting the user for y or n (strict).

$input = $cli->confirm('Continue?');

if ($input->confirmed()) {
    // do something...
}

$cli->password()

Hiding text the user is typing.

$input = $cli->password('Please enter password:');
$pwd   = $input->prompt();

$cli->checkboxes()

Presenting the user with a set of interactive options. The user can select multiple of them.

$options = ['Ice Cream', 'Mixtape', 'Teddy Bear', 'Pizza', 'Puppies'];
// or as associative array
$options = [
    'option1' => 'Ice Cream',
    'option2' => 'Mixtape',
    'option3' => 'Teddy Bear',
    'option4' => 'Pizza',
    'option5' => 'Puppies'
];

$input  = $cli->checkboxes('Please send me all of the following:', $options);
$result = $input->prompt();

You will get an array back with the checked options (an empty array in the case of no checked options). If you provide an associative array as the options, an array of the selected keys will be provided as the result.

$cli->radio()

Presenting the user with a set of interactive options. The user can only select one of them.

$options = ['Ice Cream', 'Mixtape', 'Teddy Bear', 'Pizza', 'Puppies'];
// or as associative array
$options = [
    'option1' => 'Ice Cream',
    'option2' => 'Mixtape',
    'option3' => 'Teddy Bear',
    'option4' => 'Pizza',
    'option5' => 'Puppies'
];

$input  = $cli->radio('Please send me one of the following:', $options);
$result = $input->prompt();

The result will be a string, not an array (the selected key in the case of an associative array).

Advanced Styling

Combinations

Chaining any of the style to get what you want.

$cli->backgroundBlue()->green()->bold()->out('Fusce eget faucibus eros.');

Combining styles into one method.

$cli->backgroundBlueGreenBold('Fusce eget faucibus eros.');

You can apply more than one format to an output, but only one foreground and one background color.

Tags

Applying a color/background color/format to just part of an output.

$cli->blue('Please <light_red>remember</light_red> to <bold><yellow>restart</yellow></bold> the server.');

You can use any of the color or formatting keywords (snake cased) as tags.

Prepend the color with background_ to use a background color tag.

$cli->blue('Please <background_light_red>remember</background_light_red> to restart the server.');

Custom Styles

Adding your own custom colors.

$cli->style->addColor('lilac', 38);

Once you’ve added the color, you can use it like any of the other colors.

$cli->lilac('What a pretty color.');
$cli->backgroundLilac()->out('This background is a pretty color.');
$cli->out('Just this <lilac>word</lilac> is a pretty color.');
$cli->out('Just this <background_lilac>word</background_lilac> is a pretty color.');

Adding your own commands using either a string or an array of styles, just make sure that the style is defined already.

$cli->style->addCommand('rage', 'cyan');
$cli->rage('SOMETHING IS MESSED UP.');

$cli->style->addCommand('holler', ['underline', 'green', 'bold']);
$cli->holler('Yo, what up.');

It is possible to override any existing command.

$cli->style->addCommand('error', 'light_blue');
$cli->error('Whelp. That did not turn out so well.');