tomnomnom/phargs

A toolkit for writing CLI scripts in PHP

0.0.5 2013-02-25 20:55 UTC

This package is not auto-updated.

Last update: 2024-03-16 11:20:11 UTC


README

Phargs is a toolkit for writing CLI scripts in PHP; it was born out of frustration, anger, and boilerplate déjà vu. Pull requests, issues, and suggestions are always welcome.

Phargs' main asset is its argument processor, but the output tools are pretty useful too.

Everything in Phargs is available through \Phargs\Factory.

Contents

This README file is a little long, so here's a breakdown of the contents:

Installation

Phargs is available on Packagist so you can install it using Composer. Just specify it as a dependency in your composer.json:

{
    "require": {
        "tomnomnom/phargs": "0.0.5"
    }
}

Then run composer install:

▶ composer install
Loading composer repositories with package information
Installing dependencies
  - Installing tomnomnom/phargs (0.0.2)
    Loading from cache

Writing lock file
Generating autoload files

Once installed you can use the composer autoloader instead of the Phargs/Init.php script that the included examples use:

<?php
require __DIR__.'/vendor/autoload.php';

$factory = new \Phargs\Factory();
$screen = $factory->screen();

$screen->outln("Hello, World!");

Argument processing

The getopt interface isn't the most friendly thing in the world, Phargs tries to make your life a bit easier.

The argument processor is available via \Phargs\Factory::args().

Flags

A flag is an argument that turns functionality on or off. Common examples are -h to display a help message or --verbose to display more output.

Basic usage

Phargs needs to be told to expect a flag in order to use it.

<?php
// ./Examples/Flags.php

// Bootstrap Phargs
include __DIR__.'/../Phargs/Init.php';

// Everything in Phargs is available via the Factory
$factory = new \Phargs\Factory();

// Get an argument processor
$args = $factory->args();

// Expect the -h flag to be an argument
$args->expectFlag('-h');

if ($args->flagIsSet('-h')){
  echo "Help flag is set\n";
} else {
  echo "Help flag is not set";
}
▶ php ./Examples/Flags.php -h
Help flag is set
▶ php ./Examples/Flags.php
Help flag is not set

Flag aliases

You can alias flags to make your script more user friendly. Phargs supports both long (e.g. --help) and short (e.g. -h) flags.

<?php
// ./Examples/FlagAliases.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$args = $factory->args();

$args->expectFlag('-h');

// Alias the -h flag to --help so either can be used
$args->addFlagAlias('-h', '--help');

// You could check for --help instead of -h here and it would still work
if ($args->flagIsSet('-h')){
  echo "Help flag is set\n";
} else {
  echo "Help flag is not set\n";
}
▶ php ./Examples/FlagAliases.php -h
Help flag is set
▶ php ./Examples/FlagAliases.php --help
Help flag is set

Compound flags

Phargs also supports compound flags; like how you might run grep -Hnr $searchString *.

<?php
// ./Examples/CompoundFlags.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$args = $factory->args();

$args->expectFlag('-H');
$args->expectFlag('-n');
$args->expectFlag('-r');

if ($args->flagIsSet('-H')){
  echo "-H flag is set\n";
}
if ($args->flagIsSet('-n')){
  echo "-n flag is set\n";
}
if ($args->flagIsSet('-r')){
  echo "-r flag is set\n";
}
▶ php ./Examples/CompoundFlags.php -Hnr
-H flag is set
-n flag is set
-r flag is set
▶ php ./Examples/CompoundFlags.php -H -nr
-H flag is set
-n flag is set
-r flag is set
▶ php ./Examples/CompoundFlags.php -Hni # Note: 'i' is unexpected
-H flag is set
-n flag is set
▶ php ./Examples/CompoundFlags.php -n -r
-n flag is set
-r flag is set

Params

A param is an argument that provides a value. They come in 4 flavours:

  • Long, with an equals (e.g. --count=5)
  • Long, with a space (e.g. --count 5)
  • Short, with a space (e.g. -c 5)
  • Short, without a space (e.g. -c5)

Basic usage

Like with flags, you must tell Phargs to expect a param. Unlike flags, you can also get the value of a param:

<?php
// ./Examples/Params.php

// Bootstrap Phargs
include __DIR__.'/../Phargs/Init.php';

// Everything in Phargs is available via the Factory
$factory = new \Phargs\Factory();

// Get an argument processor
$args = $factory->args();

// Expect the --count param
$args->expectParam('--count');

if ($args->paramIsSet('--count')){
  echo "--count param is set\n";
  echo "--count value is: ";
  echo $args->getParamValue('--count').PHP_EOL;
} else {
  echo "--count param is not set\n";
}
▶ php ./Examples/Params.php --count=5
--count param is set
--count value is: 5
▶ php ./Examples/Params.php --count 5
--count param is set
--count value is: 5
▶ php ./Examples/Params.php --help
--count param is not set

Param aliases

Like flags, params can be aliased:

<?php
// ./Examples/ParamAliases.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$args = $factory->args();

// Expect the --count param
$args->expectParam('--count');

// Alias --count to -c so that either can be used
$args->addParamAlias('--count', '-c');

if ($args->paramIsSet('--count')){
  echo "--count param is set\n";
  echo "--count value is: ";
  echo $args->getParamValue('-c').PHP_EOL;
} else {
  echo "--count param is not set\n";
}
▶ php ./Examples/ParamAliases.php --count=5
--count param is set
--count value is: 5
▶ php ./Examples/ParamAliases.php -c 5
--count param is set
--count value is: 5
▶ php ./Examples/ParamAliases.php -c5
--count param is set
--count value is: 5

Required params

In the examples so far Phargs has expected to see params, but it doesn't mind if they're not there. If a param is important enough you can require that it exists and then check that all requirements are met:

<?php
// ./Examples/RequiredParams.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$args = $factory->args();

// Require some params
$args->requireParam('--count');
$args->requireParam('--number');

// Check that all argument requirements are met
if ($args->requirementsAreMet()){
  echo "All arg requirements are met\n";
} else {
  echo "Not all arg requirements are met\n";
}
▶ php ./Examples/RequiredParams.php --count=4 --number=5
All arg requirements are met
▶ php ./Examples/RequiredParams.php --count=4 
Not all arg requirements are met

Residual args

Residual args are the arguments left over when expected params and flags have been removed. For example:

./command -v help merge

Assuming the -v flag is expected by Phargs: help and merge are considered to be residual args. Residual args are zero-indexed, and their indexes remain the same regardless of where any expected flags or params appear in the argument list.

You can get one, all, or a range of residual args:

<?php
// ./Examples/ResidualArgs.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$args = $factory->args();

// We're expecting some arguments
$args->expectParam('--count');
$args->expectFlag('-h');

// Arguments we're not expecting are considered 'residual'
echo "Residual arg #0: ".$args->getResidualArg(0).PHP_EOL;
echo "All residual args: ".implode(', ', $args->getResidualArgs()).PHP_EOL;
echo "First two residual args: ".implode(', ', $args->getResidualArgs(0, 2)).PHP_EOL;
▶ php ./Examples/ResidualArgs.php -h help merge
Residual arg #0: help
All residual args: help, merge
First two residual args: help, merge
▶ php ./Examples/ResidualArgs.php help -h merge
Residual arg #0: help
All residual args: help, merge
First two residual args: help, merge
▶ php ./Examples/ResidualArgs.php help -h merge this thing
Residual arg #0: help
All residual args: help, merge, this, thing
First two residual args: help, merge

Outputting to the screen

Phargs provides an interface for outputting text to the screen.

The screen interface is available via \Phargs\Factory::screen().

Basic usage

Amongst other things, the screen interface provides methods to write to stdout and stderr, with or without trailing newline characters. It also provides some methods that are useful when debugging.

<?php
// ./Examples/ScreenBasic.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();

// Get a screen interface
$screen = $factory->screen();

$screen->out("Hello, ");
$screen->outln("World!");

$screen->err("Error ");
$screen->errln("message");

$screen->printf("When in %s".PHP_EOL, "Rome");

$testVar = array(1, 2, 3);
$screen->varExport($testVar);

$screen->log('A log message');
▶ php ./Examples/ScreenBasic.php 
Hello, World!
Error message
When in Rome
array (
  0 => 1,
  1 => 2,
  2 => 3,
)
2012-12-22T15:16:50+00:00: A log message

Colors

Although difficult to demonstrate in a README file, Phargs supports ANSI colors.

<?php
// ./Examples/ScreenColors.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();

// Get a screen interface
$screen = $factory->screen();

$screen->outln("Red", 'red');
$screen->outln("Red with a white background", "red", "white");
$screen->outln("Red with a white background, underlined", "red", "white", "underline");
▶ php ./Examples/ScreenColors.php 
Red
Red with a white background
Red with a white background, underlined

They really are in color; honest!

8 colors are supported:

  • black
  • red
  • green
  • yellow
  • blue
  • purple
  • cyan
  • white

3 different styles are supported:

  • regular
  • bold
  • underline

Prompting for input

Phargs has an interface for prompting for user input.

The prompter is available via \Phargs\Factory::prompter().

Basic usage

The prompt method can be used to prompt the user for some input. The trailing newline character is removed.

<?php
// ./Examples/PrompterBasic.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$screen = $factory->screen();

// Get a prompter
$prompter = $factory->prompter();

// Prompt for some input
$name = $prompter->prompt('What is your name? ');

// Do something with the response
$screen->outln("Hello, {$name}!");
▶ php ./Examples/PrompterBasic.php 
What is your name? Tom
Hello, Tom!

Required input

You can also require that a user input some information, optionally displaying a message when they don't.

<?php
// ./Examples/PrompterRequired.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$screen = $factory->screen();

// Get a prompter
$prompter = $factory->prompter();

// Prompt for some required input
$name = $prompter->promptRequired('What is your name? ', 'No name entered!');

// Do something with the response
$screen->outln("Hello, {$name}!");
▶ php ./Examples/PrompterRequired.php 
What is your name? 
No name entered!
What is your name? Tom
Hello, Tom!

Formatting

Tables

The table formatter works out how wide to make each column so that everything lines up. It's available via \Phargs\Factory::table().

<?php
// ./Examples/Table.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$screen = $factory->screen();

// Get a table formatter
$table = $factory->table();

$table->setFields(array('id', 'name'));
$table->addRows(array(
  array(1, 'Tom'),
  array(2, 'Dick'),
  array(3, 'Harry'),
));

$screen->out($table);
▶ php ./Examples/Table.php
--------------
| id | name  |
--------------
| 1  | Tom   |
| 2  | Dick  |
| 3  | Harry |
--------------

TSV

The TSV (Tab Separated Values) formatter is very similar to the Table formatter. It's available via \Phargs\Factory::tsv().

<?php
// ./Examples/Tsv.php

include __DIR__.'/../Phargs/Init.php';
$factory = new \Phargs\Factory();
$screen = $factory->screen();

// Get a TSV formatter
$table = $factory->tsv();

$table->setFields(array('id', 'name'));
$table->addRows(array(
  array(1, 'Tom'),
  array(2, 'Dick'),
  array(3, 'Harry'),
));

$screen->out($table);
▶ php ./Examples/Tsv.php
id      name
1       Tom
2       Dick
3       Harry

Requirements

  • Linux of some description
  • PHP 5.3 or newer

Testing

You can run the full test suite by running:

▶ phpunit

The tests are actually split up into 3 suites, which can be run individually:

▶ phpunit --filter Unit
▶ phpunit --filter Integration
▶ phpunit --filter FullStack

The repo is hooked up to Travis CI. You can see the state of the master branch and the build history on the Phargs Travis CI page. The full test suite runs under PHP 5.3 and PHP 5.4.