pwwang/args.php

A php command line arguments handling library

v1.0.2 2016-02-03 07:38 UTC

This package is auto-updated.

Last update: 2024-11-28 08:20:20 UTC


README

A cool and strong php command line arguments handling library

Features

  • It supports differents format of command line arguments.
    prog -a1 -b 2 --color red --dist=./out -vvv
  • It supports different types of options.
    • array (prog -a 1 2 or prog -a 1 -a 2)
    • bool (prog -a 1 or prog -a true)
    • flag (prog -useX)
    • string (prog -a somestring)
    • string with Regexp constraint
  • It can customize the usage/description of a program/command
  • It supports commands (and commands of commands :)
  • You can load the configuration from a config file
  • You can group your options/commands
  • ...

Install

Install via Composer:

"require": {
    "pwwang/args.php": "*"
}

or
composer require pwwang/args.php

Suggests:

  • kevinlebrun/colors.php: Colorize PHP cli output,
  • raveren/kint: Pretty var_dump/print_r

Examples

A simple one

<?php
require "vendor/autoload.php";
// or $args = new pw\Args\Args();
$args = pw\Args\Args::factory();
$opt  = $args->option ()
		->array ()
		->desc ('Input files.')
		->require ();
$args->done ();

Kint::dump($args->get()); 

Shapshort-simple Simple-example

Shapshort-simple Simple-example

To access a single option value:

$args[""] === ["composer.json", "composer.lock"]; // or
$opt->getValue();

Configure your own help flag

$args = pw\Args\Args::factory()
		->setHelpOpts ('-?, --HELP')
		->option ('a')
		->desc ('An option.')
		->default (1)
		->end();
$args->done ();

CustomHelpFlag

Show option value types

(Types supported: bool, array, string (with regexp validator), flag, incr (increment option like -vvv)

$args = pw\Args\Args::factory()
		->helpOnBald()
		->showTypes()
		->option ('a')
		->desc ('An option.')
		->require ()
		->array()
		->end();
$args->done ();

showTypes

Tight mode (like prog -a1 -b2)

$args = pw\Args\Args::factory()->allowNoGap();
$args->option ('a');
$args->option ('b');
$args->done ();
Kint::dump ($args->get());

We can get following outputs by running tightMode.php -a1 -b2 or tightMode.php -a 1 -b 2

┌──────────────────────────────────────────────────────────────────────────────┐
│                                 $args->get()                                        │
└──────────────────────────────────────────────────────────────────────────────┘
array (4) [
    'a' => string (1) "1"
    'b' => string (1) "2"
    'h' => bool FALSE
    'help' => bool FALSE
]
════════════════════════════════════════════════════════════════════════════════

Group your options

$args = pw\Args\Args::factory();
$args->helpOptGroup ('Group1 options');
$args->option ('a')->desc('Option a')->group ('Group1 options');
$args->option ('b')->desc('Option b')->group ('Group1 options');
$args->option ('c')->desc('Option c')->group ('Group2 options');
$args->option ('d')->desc('Option d')->group ('Group2 options');
$args->done ();

showTypes

Callbacks

You can use callbacks to change/validate the value of an option.

$args = pw\Args\Args::factory ()
	->option ("file")
	->require()
	->callback (function($opt) {
		$val = $opt->getValue ();
		if (!is_file($val)) return false;
		$opt->setValue (fopen ($val, "r"));
	}, "File does not exist.")
	->end()
	->done();

echo fgets($args["file"]) . PHP_EOL;
fclose ($args["file"]);

Run: php examples/callbacks.php -file NONEXISTFILE will raise an error Error: File does not exist.
Run: php examples/callbacks.php -file README.md will print # args.php.

Commands

$args = pw\Args\Args::factory ();
$cmd1 = $args -> command ("command1")
    -> desc    ('The first command')
	
    -> option  ("b")
    -> alias   ("B")
    -> long    ("bbc")
    -> desc    ("Option b")
    -> default ("10")
    -> end     ()
    
    -> option  ("c")
    -> long    ("optc")
    -> bool    ()
    -> default (true)
    -> desc    ("Option c, a bool option")
    -> end     ();
$cmd2 = $args -> command ("command2")
	-> aka     ('command-2')
	-> desc    ('The second command')
    -> option  ("d")
    -> long    ("optd")
    -> flag    ()
    -> desc    ("Whether something is done.")
    -> end     ()
    
    -> option  ("e")
    -> array   ()
    -> require ()
    -> desc    ("Option e")
    -> callback(function ($opt) { $opt->setValue (implode(",", $opt->getValue())); })
    -> end     ();
$args -> done();
// To get the values:
$b = $cmd1->getOption("b")->getValue(); // or
$b = $cmd1["b"]; // or
$b = $args["command1.b"];
$d = $args["command2.optd"]; // or
$d = $args["command-2.optd"];

Chaining

$args = pw\Args\Args::factory ()
	-> helpOnBald()
	-> usage ("{prog} <command> [options ...]")
	-> option ("a")
	-> desc ("Option a")
	-> end () // return to $args
	-> option ("b") // so that I can add another option
	-> end () // return to $args
	-> command ("command1") // add a command
	-> option ("a") // add an option for command1
	-> end () // return to command1 object
	-> end () // return to $args
	-> done (); // returns $args

Load configuration from array

$args = pw\Args\Args::factory()
	-> loadFromArray ([
		"helpOptGroup" => "Group1 options",
		"options" => [
			"a" => [
				"desc" => "Option a",
				"group" => "Group1 options"
			],
			"b" => [
				"desc" => "Option b",
				"group" => "Group1 options"
			],
			"c" => [
				"desc" => "Option c",
				"group" => "Group2 options"
			],
			"d" => [
				"desc" => "Option d",
				"group" => "Group2 options"
			]
		]
	]);
$args-> done ();

Load from configuration file

If you don't want the configure take too much space in your script file (say script.php, you can define them in JSON format in a separate file. (script.args.json by default)

$args = pw\Args\Args::factory()->done ();
// or you can define in a different file
$args = pw\Args\Args::factory($configfile)->done ();

script.args.json:

{
	"optGroupOrder": "Optional options, Required options",
	"cmdGroupOrder": "Group1 commands, Group2 commands",
	"helpOptGroup" : "Optional options",
	"helpCmdGroup" : "Group2 commands",
	"showTypes"    : true,
	"options"      : {
		"a" : {
			"aka"    : "a1",
			"long"   : "abc",
			"desc"   : "Option a",
			"require": true,
			"group"  : "Required options"
		}
	},
	"commands"    : {
		"g1-cmd" : {
			"desc"    : "The command belongs to group1",
			"group"   : "Group1 commands",
			"options" : {
				"b" : {
					"alias"   : "b1",
					"long"    : "bbc",
					"desc"    : "Option b",
					"default" : 10,
					"group"   : "Optional options"
				}
			}
		},
		"g2-cmd" : {
			"desc"    : "The command belongs to group2",
			"group"   : "Group2 commands",
			"options" : {
				"c" : {
					"long"   : "optc",
					"type"   : "bool",
					"default": true,
					"group"  : "Optional options",
					"desc"   : "Option c, a bool option"
				},
				"d" : {
					"long"   : "optd",
					"group"  : "Optional options",
					"type"   : "flag",
					"desc"   : "Whether something is done."
				},
				"e" : {
					"type"     : "array",
					"require"  : true,
					"group"    : "Required options",
					"desc"     : "Option e",
					"callback" : "PHP: function ($opt) { $opt->setValue (implode(\",\", $opt->getValue())); }"
				},
				"" : {
					"type"     : "array",
					"require"  : true,
					"group"    : "Required options",
					"desc"     : "Option f"
				}
			}
		}
	}
}

Documentation

Documentation

API

API