• Stars
    star
    144
  • Rank 255,590 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 13 years ago
  • Updated over 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,209
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
214
star
8

vikube.vim

Operating Kubernetes Cluster from Vim, in Vim
Vim Script
197
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
183
star
10

guts

Guts is a new language beyonds PHP.
Go
156
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
119
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
54
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
42
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
38
star
24

PHPRelease

PHPRelease manages your package release process.
PHP
32
star
25

requestgen

request builder generator for Go!
Go
32
star
26

cpan.vim

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

php-ext-skeleton

The minimal PHP extension skeleton
C
29
star
28

reducer

Fast Map & Reduce php7 extension for large array
C
27
star
29

Plack-Middleware-OAuth

Plack Middleware for OAuth1 and OAuth2
Perl
27
star
30

goenv

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

phpunit.vim

phpunit plugin for Vim editor
Vim Script
25
star
32

callbackgen

callbackgen generates callback pattern for your callback fields.
Go
25
star
33

typeloy

typeloy is a meteor application deployment tool written in typescript.
TypeScript
25
star
34

vim-dev-plugin

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

cpansearch

CPAN module search in C.
C
24
star
36

vim-makefile

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

GoTray

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

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
39

FastCommit

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

zh-stroke-data

ๅธธ็”จๅœ‹ๅญ—ๆจ™ๆบ–ๅญ—้ซ”็ญ†ๅŠƒ XML ่ณ‡ๆ–™ๆช”
JavaScript
22
star
41

WireRoom

Collaborative Chatroom For Hackers
JavaScript
20
star
42

gatsby

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

SimpleBench

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

WebUI

Abstract PHP interface for building common HTML components with microdata
PHP
20
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

gitorbit

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

jira.sh

JIRA Client for Bash Scripts
Shell
18
star
48

perldoc-zhtw-translation

Perldoc Translation in zh-tw
Perl
18
star
49

LazyBone

MicroFramework: LazyRecord + BackBone + Roller RESTful Router
JavaScript
18
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

jchash

Jump Consistent Hashing Algorithm implemented in PHP 7 Extension
C
16
star
53

ClassMap

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

router-benchmark

PHP Router Benchmark
PHP
14
star
55

rockhopper

rockhopper is an embeddable migration tool written by Go
Go
14
star
56

go-aes-crypt

Go
13
star
57

php-FastRequire

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

GrindKit

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

MiniPear

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

simple-commenter.vim

simple commenter plugin
Vim Script
11
star
61

cascading.vim

Vim Script
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
10
star
66

PJSON

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

kubernetes-term

Connecting xterm.js to kubernetes exec spdy stream with socket.io
Go
9
star
68

perl-poppler

basic porting of poppler
Perl
9
star
69

phpkmp

Knuth-Morris-Pratt algorithm implemented in C, PHP and PHP Extension
C
9
star
70

PerlTW-Planet

Perl Taiwan Planet
CSS
9
star
71

vagrant-kubeadm

Vagrant for kubeadm
Shell
8
star
72

sid

Sequential ID generator as a micro-service, implemented in Go
Go
8
star
73

Git-Release

A Git Release Manager
Perl
8
star
74

ZLogger

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

d3-kmeans

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

alpine-dlib

base image for dlib application
Shell
8
star
77

lftp-sync.vim

lftp sync plugin for vim.
Vim Script
8
star
78

vimomni.vim

a better completion for VimL.
Vim Script
8
star
79

requestgen-tutorial

Go
8
star
80

universal

The general purpose standard library for PHP.
PHP
8
star
81

glusterfs-deploy

Shell
7
star
82

inflect

Inflector for Go
Go
7
star
83

taipei.pm

Taipei.pm
Perl
7
star
84

ssh-authorizedkey

AuthorizedKey Encoder implemented in Go
Go
7
star
85

chrome-extension-template

7
star
86

action-js

The powerful javascript library for connecting form components with backend protocols.
JavaScript
7
star
87

bufexplorer

Vim Script
7
star
88

more.vim

ไธ€็”จๅฐฑๆ„›ไธŠ็š„ไธญๆ–‡ๅ‡ๆ–‡็”ข็”Ÿๅ™จไน‹ Vim Plugin
Vim Script
7
star
89

c9s

7
star
90

Kendo

The Powerful Access Control Framework
PHP
7
star
91

CacheKit

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

VersionKit

Version String Utilities
PHP
7
star
93

PHPUnit_TestMore

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

dlib-serving

Run dlib model inference as a gRPC server
CMake
7
star
95

CurlKit

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

zhwrap.vim

Chinese text wrapping vim plugin.
Vim Script
6
star
97

go-duck

Duck Typing for Go
Go
6
star
98

model-serving-proto

gRPC protobuf files that define the common model serving interface
Python
6
star
99

OAuthProvider

PHP
6
star
100

php-fileutil

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