1# PHP-CLI 2 3PHP-CLI is a simple library that helps with creating nice looking command line scripts. 4 5It takes care of 6 7- **option parsing** 8- **help page generation** 9- **automatic width adjustment** 10- **colored output** 11- **optional PSR3 compatibility** 12 13It is lightweight and has **no 3rd party dependencies**. Note: this is for non-interactive scripts only. It has no readline or similar support. 14 15## Installation 16 17Use composer: 18 19```php composer.phar require splitbrain/php-cli``` 20 21## Usage and Examples 22 23Minimal example: 24 25```php 26#!/usr/bin/php 27<?php 28require __DIR__ . '/../vendor/autoload.php'; 29use splitbrain\phpcli\CLI; 30use splitbrain\phpcli\Options; 31 32class Minimal extends CLI 33{ 34 // register options and arguments 35 protected function setup(Options $options) 36 { 37 $options->setHelp('A very minimal example that does nothing but print a version'); 38 $options->registerOption('version', 'print version', 'v'); 39 } 40 41 // implement your code 42 protected function main(Options $options) 43 { 44 if ($options->getOpt('version')) { 45 $this->info('1.0.0'); 46 } else { 47 echo $options->help(); 48 } 49 } 50} 51// execute it 52$cli = new Minimal(); 53$cli->run(); 54``` 55 56![Screenshot](screenshot.png) 57 58 59The basic usage is simple: 60 61- create a class and ``extend splitbrain\phpcli\CLI`` 62- implement the ```setup($options)``` method and register options, arguments, commands and set help texts 63 - ``$options->setHelp()`` adds a general description 64 - ``$options->registerOption()`` adds an option 65 - ``$options->registerArgument()`` adds an argument 66 - ``$options->registerCommand()`` adds a sub command 67- implement the ```main($options)``` method and do your business logic there 68 - ``$options->getOpts`` lets you access set options 69 - ``$options->getArgs()`` returns the remaining arguments after removing the options 70 - ``$options->getCmd()`` returns the sub command the user used 71- instantiate your class and call ```run()``` on it 72 73More examples can be found in the examples directory. Please refer to the [API docs](https://splitbrain.github.io/php-cli/) 74for further info. 75 76## Exceptions 77 78By default, the CLI class registers an exception handler and will print the exception's message to the end user and 79exit the programm with a non-zero exit code. You can disable this behaviour and catch all exceptions yourself by 80passing false to the constructor. 81 82You can use the provided ``splitbrain\phpcli\Exception`` to signal any problems within your main code yourself. The 83exception's code will be used as the exit code then. 84 85Stacktraces will be printed on log level `debug`. 86 87## Colored output 88 89Colored output is handled through the ``Colors`` class. It tries to detect if a color terminal is available and only 90then uses terminal colors. You can always suppress colored output by passing ``--no-colors`` to your scripts. 91Disabling colors will also disable the emoticon prefixes. 92 93Simple colored log messages can be printed by you using the convinence methods ``success()`` (green), ``info()`` (cyan), 94``error()`` (red) or ``fatal()`` (red). The latter will also exit the programm with a non-zero exit code. 95 96For more complex coloring you can access the color class through ``$this->colors`` in your script. The ``wrap()`` method 97is probably what you want to use. 98 99The table formatter allows coloring full columns. To use that mechanism pass an array of colors as third parameter to 100its ``format()`` method. Please note that you can not pass colored texts in the second parameters (text length calculation 101and wrapping will fail, breaking your texts). 102 103## Table Formatter 104 105The ``TableFormatter`` class allows you to align texts in multiple columns. It tries to figure out the available 106terminal width on its own. It can be overwritten by setting a ``COLUMNS`` environment variable. 107 108The formatter is used through the ``format()`` method which expects at least two arrays: The first defines the column 109widths, the second contains the texts to fill into the columns. Between each column a border is printed (a single space 110by default). 111 112See the ``example/table.php`` for sample usage. 113 114Columns width can be given in three forms: 115 116- fixed width in characters by providing an integer (eg. ``15``) 117- precentages by provifing an integer and a percent sign (eg. ``25%``) 118- a single fluid "rest" column marked with an asterisk (eg. ``*``) 119 120When mixing fixed and percentage widths, percentages refer to the remaining space after all fixed columns have been 121assigned. 122 123Space for borders is automatically calculated. It is recommended to always have some relative (percentage) or a fluid 124column to adjust for different terminal widths. 125 126The table formatter is used for the automatic help screen accessible when calling your script with ``-h`` or ``--help``. 127 128## PSR-3 Logging 129 130The CLI class is a fully PSR-3 compatible logger (printing colored log data to STDOUT and STDERR). This is useful when 131you call backend code from your CLI that expects a Logger instance to produce any sensible status output while running. 132 133If you need to pass a class implementing the `Psr\Log\LoggerInterface` you can do so by inheriting from one of the two provided classes implementing this interface instead of `splitbrain\phpcli\CLI`. 134 135 * Use `splitbrain\phpcli\PSR3CLI` if you're using version 2 of PSR3 (PHP < 8.0) 136 * Use `splitbrain\phpcli\PSR3CLIv3` if you're using version 3 of PSR3 (PHP >= 8.0) 137 138The resulting object then can be passed as the logger instance. The difference between the two is in adjusted method signatures (with appropriate type hinting) only. Be sure you have the suggested `psr/log` composer package installed when using these classes. 139 140Note: if your backend code calls for a PSR-3 logger but does not actually type check for the interface (AKA being LoggerAware only) you can also just pass an instance of `splitbrain\phpcli\CLI`. 141 142## Log Levels 143 144You can adjust the verbosity of your CLI tool using the `--loglevel` parameter. Supported loglevels are the PSR-3 145loglevels and our own `success` level: 146 147* debug 148* info 149* notice 150* success (this is not defined in PSR-3) 151* warning 152* error 153* critical 154* alert 155* emergency 156 157![Screenshot](screenshot2.png) 158 159Convenience methods for all log levels are available. Placeholder interpolation as described in PSR-3 is available, too. 160Messages from `warning` level onwards are printed to `STDERR` all below are printed to `STDOUT`. 161 162The default log level of your script can be set by overwriting the `$logdefault` member. 163 164See `example/logging.php` for an example. 165