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