Another Command Line Argument Parser

Overview

Optparse — Another Command Line Argument Parser

Install

1. Get composer.

2. Put this into your local composer.json:

{
  "require": {
    "chh/optparse": "*@dev"
  }
}

3. php composer.phar install

Example

hello.php:

<?php

require "vendor/autoload.php";

use CHH\Optparse;

$parser = new Optparse\Parser("Says Hello");

function usage_and_exit()
{
    global $parser;
    fwrite(STDERR, "{$parser->usage()}\n");
    exit(1);
}

$parser->addFlag("help", array("alias" => "-h"), "usage_and_exit");
$parser->addFlag("shout", array("alias" => "-S"));
$parser->addArgument("name", array("required" => true));

try {
    $parser->parse();
} catch (Optparse\Exception $e) {
    usage_and_exit();
}

$msg = "Hello {$parser["name"]}!";

if ($parser["shout"]) {
    $msg = strtoupper($msg);
}

echo "$msg\n";

Try it:

% php hello.php Christoph --shout
HELLO CHRISTOPH!

Use

There are two things you will define in the parser:

  • Flags, arguments which start with one or two dashes and are considered as options of your program.
  • Arguments, everything else which is not a flag.

The main point of interest is the CHH\Optparse\Parser, which you can use to define Flags and Arguments.

Flags

To define a flag, pass the flag's name to the addFlag method:

<?php

$parser = new CHH\Optparse\Parser;

$parser->addFlag("help");
$parser->parse();

if ($parser["help"]) {
    echo $parser->usage();
    exit;
}

A flag defined with addFlag is by default available as --$flagName. To define another name (e.g. a short name) for the flag, pass it as the value of the alias option in the options array:

<?php
$parser->addFlag("help", ["alias" => "-h"]);

This way the help flag is available as --help and -h.

Flags don't expect values following them by default. To turn this on set the flag's has_value option to true:

<?php

$parser->addFlag("name", ["has_value" => true]);
$parser->parse(['--name', 'John']);

echo "Hello World {$parser["name"]}!\n";

You can assign a default value to a flag, by setting the default option:

<?php

$parser->addFlag("pid_file", ["default" => "/var/tmp/foo.pid", "has_value" => true]);

$parser->parse([]);

echo "{$parser["pid_file"]}\n";
// Output:
// /var/tmp/foo.pid

You can also bind the flag directly to a reference, by passing the reference in the var option or by using the addFlagVar method and passing it the variable:

<?php

$foo = null;
$bar = null;

$parser->addFlag("foo", ["var" => &$foo, "has_value" => true]);
$parser->addFlagVar("bar", $bar, ["has_value" => true]);

$parser->parse(['--foo', 'foo', '--bar', 'bar']);

echo "$foo\n";
echo "$bar\n";
// Output:
// foo
// bar

The parser also supports callbacks for flags. These are passed to addFlag as last argument. The callback is called everytime the parser encounters the flag. It gets passed a reference to the flag's value (true if it hasn't one). Use cases for this include splitting a string in pieces or running a method when a flag is passed:

<?php

$parser = new Parser;

function usage_and_exit()
{
    global $parser;
    echo $parser->usage(), "\n";
    exit;
}

$parser->addFlag("help", ['alias' => '-h'], "usage_and_exit");

$parser->addFlag("queues", ["has_value" => true], function(&$value) {
    $value = explode(',', $value);
});

The call to parse takes an array of arguments, or falls back to using the arguments from $_SERVER['argv']. The parse method throws an CHH\Optparse\ArgumentException when a required flag or argument is missing, so make sure to catch this Exception and provide the user with a nice error message.

The parser is also able to generate a usage message for the command by looking at the defined flags and arguments. Use the usage method to retrieve it.

Named Arguments

Named arguments can be added by using the addArgument method, which takes the argument's name as first argument and then an array of options.

These options are supported for arguments:

  • default: Default Value (default: null).
  • var_arg: Makes this a variable length argument (default: false).
  • help: Help text, used to describe the argument in the usage message generated by usage() (default: null).
  • required: Makes this argument required, the parser throws an exception when the argument is omitted in the argument list (default: false).

As opposed to flags, the order matters in which you define your arguments.

Variable length arguments can be defined by setting the var_arg option to true in the options array. Variable arguments can only be at the last position, and arguments defined after an variable argument are never set.

<?php

$parser->addArgument("files", ["var_arg" => true]);

// Will always be null, because the value will be consumed by the
// "var_arg" enabled argument.
$parser->addArgument("foo");

$parser->parse(["foo", "bar", "baz"]);

foreach ($parser["files"] as $file) {
    echo $file, "\n";
}
// Output:
// foo
// bar
// baz

Arguments can also be retrieved by using the args, arg and slice methods:

<?php

$parser->addArgument("foo");
$parser->parse(["foo", "bar", "baz"]);

echo var_export($parser->args());
// Output:
// array("foo", "bar", "baz")

// Can also be used to fetch named arguments:
echo var_export($parser->arg(0));
echo var_export($parser->arg("foo"));
// Output:
// "foo"
// "foo"

// Pass start and length:
echo var_export($parser->slice(0, 2));
// Output:
// array("foo", "bar");

License

Copyright (c) 2012 Christoph Hochstrasser

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Issues
  • Reset value on every loop iteration.

    Reset value on every loop iteration.

    Hi,

    this pr fixes misparing of opts like: ./application -t 3 -s 7 -p 1337 -a 42

    Value needs to be resettet on every iteration, or it is not resettet.

    Thanks Valentin

    opened by vkunz 1
  • Support --flag=value

    Support --flag=value

    enhancement 
    opened by CHH 0
  • Parser::offsetExists and Parser::has

    Parser::offsetExists and Parser::has

    It would be awesome when you integrate a little shorthand for offsetExists, like "has". I think this would be pretty, pretty.

    Thank you

    opened by tyurderi 0
  • Code is not E_STRICT clean

    Code is not E_STRICT clean

    Could you please supply the correct parameters in lib / CHH / Optparse.php

    eg. insert defaults before line 54ff like:

    isset($options["alias"]) OR $options["alias"] = array(); isset($options["default"]) OR $options["default"] = NULL; isset($options["has_value"]) OR $options["has_value"] = FALSE; isset($options["help"]) OR $options["help"] = "";

    (and remove the not working "@" since PHP 5.4 with E_STRICT by default)

    $this->aliases = array_merge(array("--$name"), (array) $options["alias"]); $this->defaultValue = $options["default"]; $this->hasValue = (bool) $options["has_value"]; $this->help = $options["help"];

    Thank you very much... Sincerely yours

    opened by pkracht 0
  • Use the same internal structure for arguments & flags?

    Use the same internal structure for arguments & flags?

    Flags are kind of an argument, so they already share most of the same properties. Should this be unified?

    The addFlag method would then create an argument, but with different options set.

    question 
    opened by CHH 0
Owner
Christoph Hochstrasser
Christoph Hochstrasser
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 7.1 and above. Releases For an overview of the releas

null 312 Jan 4, 2022
A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!

CLIFramework CLIFramework is a command-line application framework, for building flexiable, simple command-line applications. Commands and Subcommands

Yo-An Lin 412 Dec 9, 2021
Lovely PHP wrapper for using the command-line

ShellWrap What is it? It's a beautiful way to use powerful Linux/Unix tools in PHP. Easily and logically pipe commands together, capture errors as PHP

James Hall 744 Dec 28, 2021
Command-Line Interface tools

Aura.Cli Provides the equivalent of request ( Context ) and response ( Stdio ) objects for the command line interface, including Getopt support, and a

Aura for PHP 102 Aug 1, 2021
👨🏻‍🚀 A command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀

Alpine Day Schedule a command-line tool that gives you the Alpine Day 2021 schedule in your timezone. ?? Quick start Requires PHP 7.4+ # First, instal

Nuno Maduro 11 Jun 10, 2021
PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal.

PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal. ??

Nuno Maduro 32 Dec 12, 2021
Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check.

Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check. Installation / Usage Requires PHP 8.0+ First, install Patr

Nuno Maduro 223 Jan 9, 2022
Twitter raffles in the command line, with PHP and minicli

Rafflebird Rafflebird is a highly experimental CLI application for giveaways / raffles on Twitter, built in PHP with Minicli. Disclaimer: The recent s

Erika Heidi 30 Jan 7, 2022
A command line code generator for Drupal.

Drupal Code Generator A command line code generator for Drupal. Installation Download the latest stable release of the code generator.

Ivan 205 Dec 27, 2021
A PHP command line tool used to install shlink

Shlink installer A PHP command line tool used to install shlink. Installation Install this tool using composer.

null 7 Jan 10, 2022
Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone. ?? Quick start Requires PHP 7.4+ # First, install: c

Nuno Maduro 94 Dec 13, 2021
Command-line control panel for Nginx Server to manage WordPress sites running on Nginx, PHP, MySQL, and Let's Encrypt

EasyEngine v4 EasyEngine makes it greatly easy to manage nginx, a fast web-server software that consumes little memory when handling increasing volume

EasyEngine 1.9k Jan 12, 2022
Generic PHP command line flags parse library

PHP Flag Generic PHP command line flags parse library Features Generic CLI options and arguments parser. Support set value data type(int,string,bool,a

PHP Toolkit 13 Jan 10, 2022
A simple command-line tool whose aim is to facilitate the continous delivery of PHP apps

Deployer Simple command-line tool that aims to facilitate the continous delivery of PHP apps, particularly Laravel apps. Imagine you want to update yo

Fernando Bevilacqua 4 Sep 8, 2021
🍃 In short, it's like Tailwind CSS, but for the PHP command-line applications.

Termwind Termwind allows you to build unique and beautiful PHP command-line applications, using the Tailwind CSS API. In short, it's like Tailwind CSS

Nuno Maduro 1.1k Jan 8, 2022
A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies.

Front End Compiler A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies. The minif

Happy Medium 2 Nov 12, 2021
php command line script to DCA crypto from Coinbase Pro

dca.php A simple php script designed to be run via the command line via a cron job. This will connect to coinbase pro and buy the crypto coins specifi

Ben Suffolk 2 Oct 22, 2021
Simple command-line tool to access HiWeb account information

Simple command-line tool to access HiWeb account information.

Milad Nekofar 1 Nov 17, 2021