• Stars
    star
    167
  • Rank 226,437 (Top 5 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 8 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP library to build command line tools

PHP-CLI

PHP-CLI is a simple library that helps with creating nice looking command line scripts.

It takes care of

  • option parsing
  • help page generation
  • automatic width adjustment
  • colored output
  • optional PSR3 compatibility

It is lightweight and has no 3rd party dependencies. Note: this is for non-interactive scripts only. It has no readline or similar support.

Installation

Use composer:

php composer.phar require splitbrain/php-cli

Usage and Examples

Minimal example:

#!/usr/bin/php
<?php
require __DIR__ . '/../vendor/autoload.php';
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;

class Minimal extends CLI
{
    // register options and arguments
    protected function setup(Options $options)
    {
        $options->setHelp('A very minimal example that does nothing but print a version');
        $options->registerOption('version', 'print version', 'v');
    }

    // implement your code
    protected function main(Options $options)
    {
        if ($options->getOpt('version')) {
            $this->info('1.0.0');
        } else {
            echo $options->help();
        }
    }
}
// execute it
$cli = new Minimal();
$cli->run();

Screenshot

The basic usage is simple:

  • create a class and extend splitbrain\phpcli\CLI
  • implement the setup($options) method and register options, arguments, commands and set help texts
    • $options->setHelp() adds a general description
    • $options->registerOption() adds an option
    • $options->registerArgument() adds an argument
    • $options->registerCommand() adds a sub command
  • implement the main($options) method and do your business logic there
    • $options->getOpts lets you access set options
    • $options->getArgs() returns the remaining arguments after removing the options
    • $options->getCmd() returns the sub command the user used
  • instantiate your class and call run() on it

More examples can be found in the examples directory. Please refer to the API docs for further info.

Exceptions

By default, the CLI class registers an exception handler and will print the exception's message to the end user and exit the programm with a non-zero exit code. You can disable this behaviour and catch all exceptions yourself by passing false to the constructor.

You can use the provided splitbrain\phpcli\Exception to signal any problems within your main code yourself. The exception's code will be used as the exit code then.

Stacktraces will be printed on log level debug.

Colored output

Colored output is handled through the Colors class. It tries to detect if a color terminal is available and only then uses terminal colors. You can always suppress colored output by passing --no-colors to your scripts. Disabling colors will also disable the emoticon prefixes.

Simple colored log messages can be printed by you using the convinence methods success() (green), info() (cyan), error() (red) or fatal() (red). The latter will also exit the programm with a non-zero exit code.

For more complex coloring you can access the color class through $this->colors in your script. The wrap() method is probably what you want to use.

The table formatter allows coloring full columns. To use that mechanism pass an array of colors as third parameter to its format() method. Please note that you can not pass colored texts in the second parameters (text length calculation and wrapping will fail, breaking your texts).

Table Formatter

The TableFormatter class allows you to align texts in multiple columns. It tries to figure out the available terminal width on its own. It can be overwritten by setting a COLUMNS environment variable.

The formatter is used through the format() method which expects at least two arrays: The first defines the column widths, the second contains the texts to fill into the columns. Between each column a border is printed (a single space by default).

See the example/table.php for sample usage.

Columns width can be given in three forms:

  • fixed width in characters by providing an integer (eg. 15)
  • precentages by provifing an integer and a percent sign (eg. 25%)
  • a single fluid "rest" column marked with an asterisk (eg. *)

When mixing fixed and percentage widths, percentages refer to the remaining space after all fixed columns have been assigned.

Space for borders is automatically calculated. It is recommended to always have some relative (percentage) or a fluid column to adjust for different terminal widths.

The table formatter is used for the automatic help screen accessible when calling your script with -h or --help.

PSR-3 Logging

The CLI class is a fully PSR-3 compatible logger (printing colored log data to STDOUT and STDERR). This is useful when you call backend code from your CLI that expects a Logger instance to produce any sensible status output while running.

If 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.

  • Use splitbrain\phpcli\PSR3CLI if you're using version 2 of PSR3 (PHP < 8.0)
  • Use splitbrain\phpcli\PSR3CLIv3 if you're using version 3 of PSR3 (PHP >= 8.0)

The 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.

Note: 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.

Log Levels

You can adjust the verbosity of your CLI tool using the --loglevel parameter. Supported loglevels are the PSR-3 loglevels and our own success level:

  • debug
  • info
  • notice
  • success (this is not defined in PSR-3)
  • warning
  • error
  • critical
  • alert
  • emergency

Screenshot

Convenience methods for all log levels are available. Placeholder interpolation as described in PSR-3 is available, too. Messages from warning level onwards are printed to STDERR all below are printed to STDOUT.

The default log level of your script can be set by overwriting the $logdefault member.

See example/logging.php for an example.

More Repositories

1

dokuwiki

The DokuWiki Open Source Wiki Engine
PHP
3,539
star
2

clipscreen

Mirror a portion of your screen to a virtual monitor for easier screen sharing.
C++
463
star
3

ReMarkableAPI

Docs and implementation of the reMarkable file sync API
PHP
374
star
4

rpibplusleaf

Raspberry Pi B+ Pinout Leaf
343
star
5

docker-phpfarm

A Dockerfile to build an image running multiple PHP versions on Apache
Shell
226
star
6

xdebug-trace-tree

Very simple XDebug trace web GUI
PHP
155
star
7

pimenu

Simple fullscreen menu system for Raspberry Pi Touchscreen
Python
132
star
8

git-pull-request

git command to automatically pull github pull requests into their own branch
Python
131
star
9

php-archive

Pure-PHP implementation to read and write TAR and ZIP archives
PHP
99
star
10

ook

A Text <-> Brainfuck/Ook webinterface
PHP
72
star
11

monsterID

The original MonsterID implementation
PHP
65
star
12

php-epub-meta

A PHP library to read and write EPub meta data
PHP
58
star
13

dokuwiki-plugin-dw2pdf

A fork of Luigi Micco's PDF export plugin for DokuWiki
PHP
55
star
14

dokuwiki-plugin-data

Add and query structured data in your DokuWiki
PHP
50
star
15

commie

commie is a pastebin script with line commenting support
JavaScript
50
star
16

crocofile

A webbased file upload manager to share files by sharing an account
JavaScript
44
star
17

dokuwiki-plugin-bureaucracy

Create forms and generate pages or emails from them
PHP
43
star
18

file-icon-generator

Generate consistent pixel perfect file icons
PHP
36
star
19

googlephonefix

Fix your Google Contact's phone numbers
JavaScript
34
star
20

dokuwiki-plugin-upgrade

Upgrade a DokuWiki installation automatically
PHP
26
star
21

bql-label-printer

Brother Label Printer UI
HTML
26
star
22

dnstunnel

A Perl script to run a DNS tunneling server
24
star
23

dokuwiki-plugin-translation

Easily setup a multi-language DokuWiki
PHP
22
star
24

dokuwiki-plugin-gallery

Creates a gallery of images from a namespace or RSS/ATOM feed in DokuWiki
PHP
21
star
25

blogrng

Discover the indieweb, one blog post at a time.
PHP
19
star
26

irclogger

A Perl/PHP tool to log an IRC channel and make it searchable on the Web
Perl
19
star
27

dokuwiki-grapher

Create graphs from DokuWiki link structures
PHP
17
star
28

giraffe

A conference schedule planner for Android
Java
17
star
29

TheBankster

A personal finance tool in PHP
PHP
17
star
30

dokuwiki-plugin-sync

Sync DokuWiki namespaces with a remote wiki on request
PHP
17
star
31

paper-backup

A bunch of shell scripts for scanning to PDF
Shell
17
star
32

dokuwiki-plugin-vshare

Plugin to easily embed videos from various video sharing sites into DokuWiki
PHP
16
star
33

dokuwiki-stickbuilder

Helps building a minimal Apache for DokuWiki-on-a-Stick
Shell
14
star
34

php-ringicon

A Indenticon/Glyphicon Library
PHP
14
star
35

TheCashster

Simple Expense Tracking App for Android with Google Sheets Sync
Java
14
star
36

dokuwiki-recover

Recover a broken DokuWiki
PHP
14
star
37

universaleditbutton

A Firefox Extension to add support for the Universal Edit Button
JavaScript
13
star
38

dokuwiki-plugin-smtp

Send DokuWiki mails via a configured SMTP server
PHP
12
star
39

dokuwiki-plugin-redirect

Redirect DokuWiki page accesses based on a central redirection list
PHP
12
star
40

imagelabeler

Add labels to an image
JavaScript
12
star
41

dokuwiki-plugin-graphviz

Create Graphviz graphs from within DokuWiki
PHP
12
star
42

openscad-projects

Various OpenScad designs for 3D printing
OpenSCAD
10
star
43

dokuwiki-plugin-captcha

Use a CAPTCHA challenge to protect DokuWiki against automated spam
PHP
10
star
44

patreon-rss

Generate an RSS feed for Patreon posts
PHP
9
star
45

dokuwiki-plugin-s5

Display a DokuWiki page as a S5 slideshow presentation
CSS
9
star
46

dokuwiki-plugin-pluginrepo

This is the - internal only - plugin used to manage dokuwiki plugins at dokuwiki.org
PHP
8
star
47

github-issues

List all open issues from all repositories of a given github user
JavaScript
8
star
48

dokuwiki-plugin-dokuteaser

internal plugin for dokuwiki.org
PHP
7
star
49

mastodon-widget

Mastodon Web Components
TypeScript
7
star
50

dokuwiki-plugin-searchindex

Searchindex Manager for DokuWiki
PHP
7
star
51

dokuwiki-downloader

Download and install DokuWiki on hosted webspace
PHP
7
star
52

dokuwiki-travis

Environment setup script for testing DokuWiki plugins on travis-ci
Shell
6
star
53

amazonwatch

monitor amazon product searches via RSS
PHP
6
star
54

semacode-php

A PHP library to create 2D semacode barcodes.
PHP
6
star
55

dokuwiki-plugin-statistics

Gather usage/view statistics of a DokuWiki
PHP
6
star
56

dokuwiki-plugin-letsencrypt

Request letsencrypt SSL certificates for your DokuWiki
PHP
5
star
57

dokuwiki-plugin-disqus

Embed Disqus discussion threads in DokuWiki pages
PHP
5
star
58

itchy

Fetch your itch.io library into an sqlite database for easier searching
PHP
5
star
59

pam-require

A simple PAM account module to require a special user or group to access a service
C
5
star
60

nyan

The technical base for the 2012 dokuwiki.org April fools prank
JavaScript
5
star
61

dokuwiki-plugin-ditaa

Renders ASCII flowcharts contained in a DokuWiki page to images
PHP
5
star
62

dokuwiki-plugin-loglog

Log DokuWiki user logins/logouts to a file
PHP
5
star
63

dokuwiki-plugin-ipban

Allows administrators and managers to ban certain IP addresses from accessing a DokuWiki
PHP
5
star
64

vagrant-windows11

Vagrant setup to spin up a Win11 instance
PowerShell
4
star
65

slika

Simple image handling for PHP
PHP
4
star
66

ds213j-minidlna

minidlna package for Synology DS213j
Shell
4
star
67

dokuwiki-plugin-swiftmail

Use SwiftMailer for sending mails from DokuWiki
PHP
4
star
68

dokuwiki-plugin-badbehaviour

Protect DokuWiki against malicious users and spiders
PHP
4
star
69

dokuwiki-plugin-talkpage

A talk page link for the DokuWiki sidebar
PHP
4
star
70

dokuwiki-plugin-toolbox

Adds various tools to the DokuWiki editor toolbar
JavaScript
4
star
71

WePing

ABANDONED. Let multiple users post to your social sites using ping.fm
PHP
4
star
72

archmage-template-modern

A template for the arCHMage CHM converter
JavaScript
4
star
73

unb2flarum

Convert a UNB Forum to a Flarum Forum
PHP
3
star
74

mtc

My Two Cents - Add comments to any PHP script.
PHP
3
star
75

dokuwiki-plugin-gchart

Create simple charts using the Google Chart API
PHP
3
star
76

archlinux-brother-hll3230cdw

Brother HL-L3230CDW PKGBUILD for ArchLinux
Shell
3
star
77

paypal-link-builder

Create Links for Paypal Purchase/Subscription
HTML
3
star
78

unb

unofficial repository for Unclassified Newsboard - our local changes are in the dokuwiki branch
PHP
3
star
79

sanity

A Perl script to sanitize file names
Perl
3
star
80

nodemcu-scripts

scripts to power my nodemcu boards
Lua
3
star
81

splitbrain

my profile
3
star
82

extm3u

Generates an extended .m3u playlist from mp3, ogg and flac files
Perl
3
star
83

dokuwiki-plugin-notfound

Display a custom page when a DokuWiki page does not exist.
PHP
3
star
84

dokuwiki-versionfix

A tool to help manage DokuWiki plugin versions
PHP
3
star
85

infra-bitters

Infrastructure Setup for my personal web server
Shell
2
star
86

dokuwiki-plugin-readability

Calculate Flesch-Kincaid and Gunning-Fog readability scores for DokuWiki pages
PHP
2
star
87

dokuwiki-plugin-xref

Easy linking to a PHPXref generated API doc from within DokuWiki pages.
PHP
2
star
88

dokuwiki-plugin-gh

DokuWiki plugin to include a syntax highlighted github file in a page
PHP
2
star
89

dokuwiki-plugin-passpolicy

better DokuWiki password security
PHP
2
star
90

dokuwiki-plugin-linkblog

personal DokuWiki plugin to aggregate various RSS feeds into a link blog. not fit for public use, yet
PHP
2
star
91

dokuwiki-plugin-gemini

Expose your wiki as a read-only gemini server
PHP
2
star
92

dokuwiki-plugin-actionrenderer

Use action events to overwrite DokuWiki's core XHTML rendering
PHP
2
star
93

musicbrowser

Make a directory of MP3 files browsable from a mobile device
PHP
2
star
94

dokuwiki-plugin-feedauth

A DokuWiki plugin to send an "authorization required" header in the feed
PHP
2
star
95

dokuwiki-plugin-anonip

A plugin to anonymize IP-Addresses within DokuWiki
PHP
2
star
96

gotextextract

Cross Platform text extractor for common office files
Go
2
star
97

mfhf

Monitoring the Mastodon Firehose in Real Time
JavaScript
2
star
98

dokuwiki-plugin-dev

The DokuWiki Developer's Tool
PHP
2
star
99

beer

My Beer Can collection
2
star
100

dokuwiki-plugin-dwquick

Internal plugin for powering the doku.wiki URL forwarder
PHP
2
star