• Stars
    star
    144
  • Rank 246,691 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

An object-oriented option parser library for PHP, which supports type constraints, flag, multiple flag, multiple values, required value checking

GetOptionKit

Code Quality

Build Status Coverage Status

Versions & Stats

Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads License

A powerful option parser toolkit for PHP, supporting type constraints, flag, multiple flag, multiple values and required value checking.

GetOptionKit supports PHP5.3, with fine unit testing with PHPUnit testing framework.

GetOptionKit is object-oriented, it's flexible and extendable.

Powering PHPBrew https://github.com/phpbrew/phpbrew, CLIFramework https://github.com/c9s/CLIFramework and AssetKit https://github.com/c9s/AssetKit

Features

  • Simple format.
  • Type constrant.
  • Multiple value, requried value, optional value checking.
  • Auto-generated help text from defined options.
  • Support app/subcommand option parsing.
  • Option Value Validator
  • Option Suggestions
  • SPL library.
  • HHVM support.

Requirements

  • PHP 5.3+

Install From Composer

composer require corneltek/getoptionkit

Supported Option Formats

simple flags:

program.php -a -b -c
program.php -abc
program.php -vvv   # incremental flag v=3
program.php -a -bc

with multiple values:

program.php -a foo -a bar -a zoo -b -b -b

specify value with equal sign:

program.php -a=foo
program.php --long=foo

with normal arguments:

program.php -a=foo -b=bar arg1 arg2 arg3
program.php arg1 arg2 arg3 -a=foo -b=bar

Option SPEC

v|verbose    flag option (with boolean value true)
d|dir:       option require a value (MUST require)
d|dir+       option with multiple values.
d|dir?       option with optional value
dir:=string  option with type constraint of string
dir:=number  option with type constraint of number
dir:=file    option with type constraint of file
dir:=date    option with type constraint of date
dir:=boolean option with type constraint of boolean
d            single character only option
dir          long option name

Command Line Forms

app [app-opts] [app arguments]

app [app-opts] subcommand [subcommand-opts] [subcommand-args]

app [app-opts] subcmd1 [subcmd-opts1] subcmd2 [subcmd-opts] subcmd3 [subcmd-opts3] [subcommand arguments....]

Documentation

See more details in the documentation

Demo

Please check examples/demo.php.

Run:

% php examples/demo.php -f test -b 123 -b 333

Print:

* Available options:
      -f, --foo <value>    option requires a value.
     -b, --bar <value>+    option with multiple value.
    -z, --zoo [<value>]    option with optional value.
          -v, --verbose    verbose message.
            -d, --debug    debug message.
                 --long    long option name only.
                     -s    short option name only.
Enabled options: 
* key:foo      spec:-f, --foo <value>  desc:option requires a value.
    value => test

* key:bar      spec:-b, --bar <value>+  desc:option with multiple value.
    Array
    (
        [0] => 123
        [1] => 333
    )

Synopsis

use GetOptionKit\OptionCollection;
use GetOptionKit\OptionParser;
use GetOptionKit\OptionPrinter\ConsoleOptionPrinter;

$specs = new OptionCollection;
$specs->add('f|foo:', 'option requires a value.' )
    ->isa('String');

$specs->add('b|bar+', 'option with multiple value.' )
    ->isa('Number');

$specs->add('ip+', 'Ip constraint' )
    ->isa('Ip');

$specs->add('email+', 'Email address constraint' )
    ->isa('Email');

$specs->add('z|zoo?', 'option with optional value.' )
    ->isa('Boolean');

$specs->add('file:', 'option value should be a file.' )
    ->isa('File');

$specs->add('v|verbose', 'verbose message.' );
$specs->add('d|debug', 'debug message.' );
$specs->add('long', 'long option name only.' );
$specs->add('s', 'short option name only.' );

$printer = new ConsoleOptionPrinter();
echo $printer->render($specs);

$parser = new OptionParser($specs);

echo "Enabled options: \n";
try {
    $result = $parser->parse( $argv );
    foreach ($result->keys as $key => $spec) {
        print_r($spec);
    }

    $opt = $result->keys['foo']; // return the option object.
    $str = $result->keys['foo']->value; // return the option value
    
    print_r($opt);
    var_dump($str);
    
} catch( Exception $e ) {
    echo $e->getMessage();
}

Documentation

See https://github.com/c9s/GetOptionKit/wiki for more details.

Option Value Type

The option value type help you validate the input, the following list is the current supported types:

  • string
  • number
  • boolean
  • file
  • date
  • url
  • email
  • ip
  • ipv4
  • ipv6
  • regex

And here is the related sample code:

$opt->add( 'f|foo:' , 'with string type value' )
    ->isa('string');

$opt->add( 'b|bar+' , 'with number type value' )
    ->isa('number');

$opt->add( 'z|zoo?' , 'with boolean type value' )
    ->isa('boolean');

$opt->add( 'file:' , 'with file type value' )
    ->isa('file');

$opt->add( 'date:' , 'with date type value' )
    ->isa('date');

$opt->add( 'url:' , 'with url type value' )
    ->isa('url');

$opt->add( 'email:' , 'with email type value' )
    ->isa('email');

$opt->add( 'ip:' , 'with ip(v4/v6) type value' )
    ->isa('ip');

$opt->add( 'ipv4:' , 'with ipv4 type value' )
    ->isa('ipv4');

$opt->add( 'ipv6:' , 'with ipv6 type value' )
    ->isa('ipv6');

$specs->add('r|regex:', 'with custom regex type value')
      ->isa('Regex', '/^([a-z]+)$/');

Please note that currently only string, number, boolean types can be validated.

ContinuousOptionParser

$specs = new OptionCollection;
$spec_verbose = $specs->add('v|verbose');
$spec_color = $specs->add('c|color');
$spec_debug = $specs->add('d|debug');
$spec_verbose->description = 'verbose flag';

// ContinuousOptionParser
$parser = new ContinuousOptionParser( $specs );
$result = $parser->parse(explode(' ','program -v -d test -a -b -c subcommand -e -f -g subcommand2'));
$result2 = $parser->continueParse();

OptionPrinter

GetOptionKit\OptionPrinter can print options for you:

* Available options:
              -f, --foo   option requires a value.
              -b, --bar   option with multiple value.
              -z, --zoo   option with optional value.
          -v, --verbose   verbose message.
            -d, --debug   debug message.
                 --long   long option name only.
                     -s   short option name only.

Command-line app with subcommands

For application with subcommands is designed by following form:

[app name] [app opts] 
             [subcommand1] [subcommand-opts]
             [subcommand2] [subcommand-opts]
             [subcommand3] [subcommand-opts]
             [arguments]

You can check the tests/GetOptionKit/ContinuousOptionParserTest.php unit test file:

// subcommand stack
$subcommands = array('subcommand1','subcommand2','subcommand3');

// different command has its own options
$subcommandSpecs = array(
    'subcommand1' => $cmdspecs,
    'subcommand2' => $cmdspecs,
    'subcommand3' => $cmdspecs,
);

// for saved options
$subcommandOptions = array();

// command arguments
$arguments = array();

$argv = explode(' ','program -v -d -c subcommand1 -a -b -c subcommand2 -c subcommand3 arg1 arg2 arg3');

// parse application options first
$parser = new ContinuousOptionParser( $appspecs );
$app_options = $parser->parse( $argv );
while (! $parser->isEnd()) {
    if (@$subcommands[0] && $parser->getCurrentArgument() == $subcommands[0]) {
        $parser->advance();
        $subcommand = array_shift( $subcommands );
        $parser->setSpecs( $subcommandSpecs[$subcommand] );
        $subcommandOptions[ $subcommand ] = $parser->continueParse();
    } else {
        $arguments[] = $parser->advance();
    }
}

Todo

  • Option Spec group.
  • option valid value checking.
  • custom command mapping.

Command Line Utility Design Concept

  • main program name should be easy to type, easy to remember.
  • subcommand should be easy to type, easy to remember. length should be shorter than 7 characters.
  • options should always have long descriptive name
  • a program should be easy to check usage.

General command interface

To list usage of all subcommands or the program itself:

$ prog help

To list the subcommand usage

$ prog help subcommand subcommand2 subcommand3

Hacking

Fork this repository and clone it:

$ git clone git://github.com/c9s/GetOptionKit.git
$ cd GetOptionKit
$ composer install

Run PHPUnit to test:

$ phpunit 

License

This project is released under MIT License.

More Repositories

1

Pux

Pux is a fast PHP Router and includes out-of-box controller tools
C
1,272
star
2

bbgo

The modern cryptocurrency trading bot framework written in Go.
Go
1,100
star
3

r3

libr3 is a high-performance path dispatching library. It compiles your route paths into a prefix tree (trie). By using the constructed prefix trie in the start-up time, you may dispatch your routes with efficiency
C
799
star
4

goprocinfo

Linux /proc info parser for Go
Go
725
star
5

CLIFramework

A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!
PHP
433
star
6

c6

Compile SASS Faster ! C6 is a SASS-compatible compiler
Go
430
star
7

gomon

Monitor for any changes in your go package and automatically restart commands (run, build, server or anything)
Go
210
star
8

vikube.vim

Operating Kubernetes Cluster from Vim, in Vim
Vim Script
195
star
9

Vimana

Vimana is an easy to use system for searching , installing, and downloading vim script. Vimana provides a command-line interface such like aptitude programe on Debian linux, for you to search , download , install , upgrade scripts from http://www.vim.org (vimonline site).
Perl
182
star
10

guts

Guts is a new language beyonds PHP.
Go
155
star
11

SQLBuilder

A powerful, fast, cross-platform SQL Builder for PHP. Convert your structured data into SQL queries with a fluent style interface and targeting on all the mainstream database (MySQL, PostgreSQL, SQLite)
PHP
142
star
12

h3

The Fast HTTP header parser library
C
130
star
13

perlomni.vim

perl omnicompletion for vim (including base class function compleltions .. etc)
Vim Script
128
star
14

github-taiwan

Taiwan Developers on Github
Perl
117
star
15

Roller

A simple, fast router for PHP5.3/4, support APC cache, RESTful, highly extendable and flexible.
PHP
86
star
16

hypergit.vim

This git plugin provides many awesome features so that you don't need to type commands anymore..
Vim Script
61
star
17

App-gh

GitHub Command-line Utility.
Perl
53
star
18

AssetKit

A Modular Asset Toolkit for PHP Applications
HTML
52
star
19

fsrename

FSRename V2 - A simple, powerful rename tool supports complex filtering
Go
51
star
20

xarray

The missing PHP array functions you are looking for, implemented in extension
C
41
star
21

ts-webpack-starter

Template project based on TypeScript, Typings, Babel and Webpack
JavaScript
41
star
22

GenPHP

A Powerful,Flexible Code Generator for PHP, can generate anything what you want for your project.
PHP
40
star
23

CodeGen

Transform your dynamic calls to static calls!
PHP
37
star
24

PHPRelease

PHPRelease manages your package release process.
PHP
32
star
25

cpan.vim

vim plugin for perl hackers. for you to search installed module/all modules and integrated with perldoc window
Vim Script
29
star
26

requestgen

request builder generator for Go!
Go
28
star
27

Plack-Middleware-OAuth

Plack Middleware for OAuth1 and OAuth2
Perl
27
star
28

goenv

Go project environment builder - build isolated workspace for your go project
27
star
29

php-ext-skeleton

The minimal PHP extension skeleton
C
27
star
30

reducer

Fast Map & Reduce php7 extension for large array
C
26
star
31

phpunit.vim

phpunit plugin for Vim editor
Vim Script
25
star
32

vim-dev-plugin

A Vim plugin for developing VimL.
Vim Script
25
star
33

vim-makefile

A lightweight non-dependency Makefile for install, uninstall, bundle, distribute Vim plugin scripts.
Vim Script
24
star
34

GoTray

Go application manager in your system status bar. (for Mac OS X)
24
star
35

typeloy

typeloy is a meteor application deployment tool written in typescript.
TypeScript
24
star
36

gsession.vim

gsession.vim saves your session files into the same directory (~/.vim/session/) by default. and auto-detect your session file to load session file when you are opening vim editor without arguments.
Vim Script
24
star
37

callbackgen

callbackgen generates callback pattern for your callback fields.
Go
23
star
38

cpansearch

CPAN module search in C.
C
23
star
39

FastCommit

Integrating GIT commit flow with your own editor easily!
23
star
40

zh-stroke-data

常用國字標準字體筆劃 XML 資料檔
JavaScript
22
star
41

gatsby

Gatsby Database Toolkit For Go (ORM, SQL Builder and SQLUtils)
Go
20
star
42

SimpleBench

SimpleBench provides suckless benchmark tools for PHP5.3
PHP
20
star
43

WebUI

Abstract PHP interface for building common HTML components with microdata
PHP
20
star
44

WireRoom

Collaborative Chatroom For Hackers
JavaScript
19
star
45

markdown-git-wiki

This is a pure git wiki (not a web server or web app), this utility only provides the functionbility of translating markdown pages into web pages. links between pages can be named by "[[Link]]". so your git wiki is just a git repository.
Perl
19
star
46

LazyBone

MicroFramework: LazyRecord + BackBone + Roller RESTful Router
JavaScript
18
star
47

gitorbit

GitHub-like Git Server, let you control the permission via mongodb or LDAP
Go
17
star
48

jira.sh

JIRA Client for Bash Scripts
Shell
17
star
49

perldoc-zhtw-translation

Perldoc Translation in zh-tw
Perl
17
star
50

php-r3

high performance r3 router extension for PHP
C
17
star
51

colorselector.vim

provide emacs-like colorscheme selector buffer.
Makefile
17
star
52

ClassMap

Generate class mapping file in PHP, to improve classloader performance.
PHP
16
star
53

jchash

Jump Consistent Hashing Algorithm implemented in PHP 7 Extension
C
15
star
54

router-benchmark

PHP Router Benchmark
PHP
14
star
55

go-aes-crypt

Go
13
star
56

php-FastRequire

SPL class loader is slow! Now you can skip the SPL functions to load your minimal class requirements directly.
13
star
57

GrindKit

PHP GrindKit for reading cachegrind compatible file.
PHP
13
star
58

MiniPear

MiniPear creates local pear channel mirrors for offline usage.
PHP
12
star
59

simple-commenter.vim

simple commenter plugin
Vim Script
11
star
60

cascading.vim

Vim Script
11
star
61

rockhopper

rockhopper is an embeddable migration tool written by Go
Go
11
star
62

ConfigKit

Toolkit for Config Files, use fast but readable YAML config file for your PHP project.
PHP
11
star
63

ClassTemplate

Class template for PHP
PHP
11
star
64

umobi

µMobi - Micro Mobile Web Framework for Smartphones & Tablets.
JavaScript
10
star
65

xfile

PHP Extension for file operations
C
9
star
66

PJSON

PJSONEncoder implements a JSON encoder with PHP object to JavaScript object translation support.
PHP
9
star
67

Git-Release

A Git Release Manager
Perl
8
star
68

ZLogger

A Simple Logger for PHP based on ZeroMQ
PHP
8
star
69

perl-poppler

basic porting of poppler
Perl
8
star
70

lftp-sync.vim

lftp sync plugin for vim.
Vim Script
8
star
71

vimomni.vim

a better completion for VimL.
Vim Script
8
star
72

kubernetes-term

Connecting xterm.js to kubernetes exec spdy stream with socket.io
Go
8
star
73

phpkmp

Knuth-Morris-Pratt algorithm implemented in C, PHP and PHP Extension
C
8
star
74

PerlTW-Planet

Perl Taiwan Planet
CSS
8
star
75

inflect

Inflector for Go
Go
7
star
76

vagrant-kubeadm

Vagrant for kubeadm
Shell
7
star
77

chrome-extension-template

7
star
78

bufexplorer

Vim Script
7
star
79

more.vim

一用就愛上的中文假文產生器之 Vim Plugin
Vim Script
7
star
80

sid

Sequential ID generator as a micro-service, implemented in Go
Go
7
star
81

d3-kmeans

A simple, lightweight, single-dimension k-means clustering algorithm implemented in javascript for d3.
JavaScript
7
star
82

alpine-dlib

base image for dlib application
Shell
7
star
83

Kendo

The Powerful Access Control Framework
PHP
7
star
84

CacheKit

Generic cache interface for FileSystem cache, Memcached, ApcCache, ... etc
PHP
7
star
85

requestgen-tutorial

Go
7
star
86

universal

The general purpose standard library for PHP.
PHP
7
star
87

PHPUnit_TestMore

let you define Test::More-like unit tests and base on the great PHPUnit testing framework.
PHP
7
star
88

CurlKit

A tiny curl based library for managing request/response/download task.
PHP
7
star
89

glusterfs-deploy

Shell
6
star
90

taipei.pm

Taipei.pm
Perl
6
star
91

ssh-authorizedkey

AuthorizedKey Encoder implemented in Go
Go
6
star
92

action-js

The powerful javascript library for connecting form components with backend protocols.
JavaScript
6
star
93

zhwrap.vim

Chinese text wrapping vim plugin.
Vim Script
6
star
94

c9s

6
star
95

go-duck

Duck Typing for Go
Go
6
star
96

OAuthProvider

PHP
6
star
97

php-fileutil

Fast File Utility Functions in PHP Extension and Pure PHP.
C
6
star
98

cssmin

Fast & Simple CSS Minify C extension for PHP
C
6
star
99

VersionKit

Version String Utilities
PHP
6
star
100

dlib-serving

Run dlib model inference as a gRPC server
CMake
6
star