PHP Classes

PHP Command Line Arguments Parser Class: Parse CLI script arguments to extract its values

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 43 All time: 10,838 This week: 68Up
Version License PHP version Categories
php_component_cli_ar 1.0.0GNU Lesser Genera...5PHP 5, Console, Parsers
Description 

Author

This class can parse CLI script arguments to extract its values.

It can take an array of arguments passed to PHP when it is run from the command line console and parses it to extract its values.

The class can return the flags that were passed to the command which are those that have - or -- prefixes, lists of argument values which are those arguments that may have appeared multiple times, and values that were passed together with the flag parameters.

Picture of nvb
  Performance   Level  
Name: nvb <contact>
Classes: 20 packages by
Country: Germany Germany
Age: ???
All time rank: 149395 in Germany Germany
Week rank: 180 Up12 in Germany Germany Up
Innovation award
Innovation award
Nominee: 12x

Winner: 1x

Example

<?php
/**
 * @author: stev leibelt <artodeto@bazzline.net>
 * @since: 2015-04-16
 */

require_once __DIR__ . '/../vendor/autoload.php';

$arguments = new \Net\Bazzline\Component\Cli\Arguments\Arguments($argv);

if (
$arguments->hasArguments()) {
    echo
$arguments->getNumberOfArguments() . ' arguments provided:' . PHP_EOL;
    foreach (
$arguments->getArguments() as $argument) {
        echo
' ' . $argument . PHP_EOL;
    }
} else {
    echo
'no values provided' . PHP_EOL;
}

if (
$arguments->hasLists()) {
    echo
$arguments->getNumberOfLists() . ' lists provided:' . PHP_EOL;
    foreach (
$arguments->getLists() as $name => $values) {
        echo
' ' . $name . PHP_EOL;
        foreach (
$values as $value) {
            echo
' ' . $value . PHP_EOL;
        }
    }
} else {
    echo
'no values provided' . PHP_EOL;
}

if (
$arguments->hasFlags()) {
    echo
$arguments->getNumberOfFlags() . ' flags provided:' . PHP_EOL;
    foreach (
$arguments->getFlags() as $flag) {
        echo
' ' . $flag . PHP_EOL;
    }
} else {
    echo
'no flags provided' . PHP_EOL;
}

if (
$arguments->hasValues()) {
    echo
$arguments->getNumberOfValues() . ' values provided:' . PHP_EOL;
    foreach (
$arguments->getValues() as $value) {
        echo
' ' . $value . PHP_EOL;
    }
} else {
    echo
'no values provided' . PHP_EOL;
}


Details

Argument Handling for PHP CLI Scripts

This project aims to deliver a easy to use and free as in freedom php command component.

The build status of the current master branch is tracked by Travis CI: Build Status Latest stable

The scrutinizer status are: code quality | build status

The versioneye status is: Dependency Status

Take a look on openhub.net.

The current change log can be found here.

Install

By Hand

mkdir -p vendor/net_bazzline/php_component_cli_arguments
cd vendor/net_bazzline/php_component_cli_arguments
git clone https://github.com/bazzline/php_component_cli_arguments .

With Packagist

composer require net_bazzline/php_component_cli_arguments:dev-master

Benefits

  • easy up handling of following kinds of arguments * flags (command -f|--force) * lists (command --foobar=foo | command -f=foo) * values values (command <value>)

Example

Simple call run.php with tons of arguments like illustrated below.

php run.php --foo bar --foobar=foo --foobar="bar" -f="foo" -f=bar -b foobar foo -flag

Generates the following output.

arguments provided:
    --foo
    bar
    --foobar=foo
    --foobar=bar
    -f=foo
    -f=bar
    -b
    foobar
    foo
    -flag
flags provided:
    foo
    b
    f
    l
    a
    g
lists provided:
    foobar
        foo
        bar
    f
        foo
        bar
values provided:
    bar
    foobar
    foo

Terms

All arguments are grouped into one of three types, flags, lists or values. Argument or parameter? I could not spot a major difference. When I think about parameters, my mind slipps into the domain of methods or functions, thats why I have decided to call them arguments. Furthermore, php.net calls the "argument list" also :-).

Flag

A flag is an argument that changes the behaviour of an command. It acts as a trigger so you can turn things on or off (best example in the world "-h|--help")

The position in a commandcall for a flag is not important, only the existence.

Valid flags are:

  • -f
  • --flag
  • -flag (shortcut for -f -l -a -g)

List

A list is an argument that contains multiple values per name.

This call

php example.php --my_list="argument one" --my_list="argument two"

would result into a list with the name "my_list" and two arguments, "argument one" and "argument two".

Lists are the most complex arguments. Like for flags, the position in a commandcall for a list usage is not important.

Valid Lists are:

  • -l=value
  • -l="val ue"
  • --list=value
  • --list="val ue"

Value

Values are straight forward arguments. You simple pass them to your command. Instead of a flag or a list, the position is important.

Valid values are:

  • value
  • "val ue"
php example.php "value one" "value two"

First value has the content "value one", second value has the content "value two".

php example.php "value two" "value one"

First value has the content "value two", second value has the content "value one".

Short Name and Long Name Notation

Flag and list arguments supporting short name ("-f") and long name ("--foo") notation. A short name is indicated by a single "-" while a long name is indicated by a double "-". The handling and the support of them is domain specific (and also a matter of tast). To merge the usage and the content for lists is not part of this component.

Why no Validation?

Validation is a complex topic. That's why I decided to not put it into the domain of this component. It would complicate the code itself. I would have created a universal validation interface that would slow down the usage of this component. Furthermore, you would have to learn a validation expression language or would have need to write code that fits my validation interface but not your "way of coding".

At the end, what is validation all about? * check if a argument (flag, list, value) is passed or not * if it is passed validate the value or if it is allowed under that circumstance (if it is right to use flag "-f" while also flag "-b" is passed etc.) * if it is not passed but was mandatory, create a specific message or throw an exception (and the same for optional arguments)

To sum it up, validation is domain specific for the validation itself and the error handling. That's why I have decided to not support it deeply. The component supports your validation implementation with the methods "hasLists()", "hasList($name)" etc.

Since I won't write "never say never", if you have a smart idea or way to easy up validation, I'm open for an question or a pull request.

What about Optional Arguments?

Optional arguments underlying the same problems as validation. It is not that easy to implement in an elegant way. It is very special/domain specific (e.g. an argument is optional if flag "--xyz" is used, otherwise mandatory). Your code has to take care if an argument is passed or not anyways. Using the available "has..."-methods should be sufficient and generic enough.

API

API is available at bazzline.net.

Other Great Components

Final Words

Star it if you like it :-). Add issues if you need it. Pull patches if you enjoy it. Write a blog entry if you use it :-D.


  Files folder image Files (12)  
File Role Description
Files folder imageExample (1 file)
Files folder imagesource (2 files)
Files folder imagetest (2 files)
Accessible without login Plain text file .scrutinizer.yml Data Auxiliary data
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (12)  /  Example  
File Role Description
  Accessible without login Plain text file run.php Example Example script

  Files folder image Files (12)  /  source  
File Role Description
  Plain text file Arguments.php Class Class source
  Plain text file Parser.php Class Class source

  Files folder image Files (12)  /  test  
File Role Description
  Plain text file ArgumentsTest.php Class Class source
  Accessible without login Plain text file bootstrap.php Aux. Auxiliary script

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:43
This week:0
All time:10,838
This week:68Up
User Comments (1)
Try again.
3 years ago (Rick Ruggiero)
20%StarStar