Console_CommandLine
[ class tree: Console_CommandLine ] [ index: Console_CommandLine ] [ all elements ]

Class: Console_CommandLine

Source Location: /Console_CommandLine-1.2.0/Console/CommandLine.php

Class Overview


Main class for parsing command line options and arguments.


Author(s):

Version:

  • Release: 1.2.0

Copyright:

  • 2007 David JEAN LOUIS

Variables

Methods


Child classes:

Console_CommandLine_Command
Class that represent a command with option and arguments.

Inherited Variables

Inherited Methods


Class Details

[line 64]
Main class for parsing command line options and arguments.

There are three ways to create parsers with this class:

  1.  // direct usage
  2.  $parser = new Console_CommandLine();
  3.  
  4.  // with an xml definition file
  5.  $parser Console_CommandLine::fromXmlFile('path/to/file.xml');
  6.  
  7.  // with an xml definition string
  8.  $validXmlString '..your xml string...';
  9.  $parser Console_CommandLine::fromXmlString($validXmlString);



[ Top ]


Class Variables

$actions = array(
        'StoreTrue'   => array('Console_CommandLine_Action_StoreTrue', true),'StoreFalse'=>array('Console_CommandLine_Action_StoreFalse',true),'StoreString'=>array('Console_CommandLine_Action_StoreString',true),'StoreInt'=>array('Console_CommandLine_Action_StoreInt',true),'StoreFloat'=>array('Console_CommandLine_Action_StoreFloat',true),'StoreArray'=>array('Console_CommandLine_Action_StoreArray',true),'Callback'=>array('Console_CommandLine_Action_Callback',true),'Counter'=>array('Console_CommandLine_Action_Counter',true),'Help'=>array('Console_CommandLine_Action_Help',true),'Version'=>array('Console_CommandLine_Action_Version',true),'Password'=>array('Console_CommandLine_Action_Password',true),'List'=>array('Console_CommandLine_Action_List',true),)

[line 222]

Array of valid actions for an option, this array will also store user registered actions.

The array format is:

 array(
      => array(, )
 )

  • Var: List of valid actions
  • Access: public

Type:   array


[ Top ]

$add_help_option =  true

[line 120]

Boolean that determine if the command line parser should add the help (-h, --help) option automatically.
  • Var: Whether to add a help option or not
  • Access: public

Type:   bool


[ Top ]

$add_version_option =  true

[line 131]

Boolean that determine if the command line parser should add the version (-v, --version) option automatically.

Note that the version option is also generated only if the version property is not empty, it's up to you to provide a version string of course.

  • Var: Whether to add a version option or not
  • Access: public

Type:   bool


[ Top ]

$args = array()

[line 191]

An array of Console_CommandLine_Argument objects.
  • Var: The arguments array
  • Access: public

Type:   array


[ Top ]

$commands = array()

[line 198]

An array of Console_CommandLine_Command objects (sub commands).
  • Var: The commands array
  • Access: public

Type:   array


[ Top ]

$description =  ''

[line 101]

A description text that will be displayed in the help message.
  • Var: Description of your program
  • Access: public

Type:   string


[ Top ]

$errors = array(
        'option_bad_name'                    => 'option name must be a valid php variable name (got: {$name})',
        'argument_bad_name'                  => 'argument name must be a valid php variable name (got: {$name})',
        'argument_no_default'                => 'only optional arguments can have a default value',
        'option_long_and_short_name_missing' => 'you must provide at least an option short name or long name for option "{$name}"',
        'option_bad_short_name'              => 'option "{$name}" short name must be a dash followed by a letter (got: "{$short_name}")',
        'option_bad_long_name'               => 'option "{$name}" long name must be 2 dashes followed by a word (got: "{$long_name}")',
        'option_unregistered_action'         => 'unregistered action "{$action}" for option "{$name}".',
        'option_bad_action'                  => 'invalid action for option "{$name}".',
        'option_invalid_callback'            => 'you must provide a valid callback for option "{$name}"',
        'action_class_does_not_exists'       => 'action "{$name}" class "{$class}" not found, make sure that your class is available before calling Console_CommandLine::registerAction()',
        'invalid_xml_file'                   => 'XML definition file "{$file}" does not exists or is not readable',
        'invalid_rng_file'                   => 'RNG file "{$file}" does not exists or is not readable'
    )

[line 74]

Error messages.
  • Var: Error messages
  • Todo: move this to Console_CommandLine_MessageProvider
  • Access: public

Type:   array


[ Top ]

$force_options_defaults =  false

[line 177]

Boolean that tells the parser to set relevant options default values, according to the option action.

Type:   bool


[ Top ]

$force_posix =  false

[line 168]

Boolean that tells the parser to be POSIX compliant, POSIX demands the following behavior: the first non-option stops option processing.
  • Var: Whether to force posix compliance or not
  • Access: public

Type:   bool


[ Top ]

$messages = array()

[line 264]

Custom errors messages for this command

This array is of the form:

  1.  <?php
  2.  array(
  3.      $messageName => $messageText,
  4.      $messageName => $messageText,
  5.      ...
  6.  );
  7.  ?>

If specified, these messages override the messages provided by the default message provider. For example:

  1.  <?php
  2.  $messages = array(
  3.      'ARGUMENT_REQUIRED' => 'The argument foo is required.',
  4.  );
  5.  ?>


Type:   array


[ Top ]

$message_provider =  false

[line 160]

The command line message provider instance.
  • Var: A message provider instance
  • Access: public



[ Top ]

$name =

[line 94]

The name of the program, if not given it defaults to argv[0].
  • Var: Name of your program
  • Access: public

Type:   string


[ Top ]

$options = array()

[line 184]

An array of Console_CommandLine_Option objects.
  • Var: The options array
  • Access: public

Type:   array


[ Top ]

$outputter =  false

[line 153]

The command line parser outputter instance.
  • Var: An outputter
  • Access: public



[ Top ]

$parent =  false

[line 207]

Parent, only relevant in Command objects but left here for interface convenience.
  • Var: The parent instance
  • Todo: move Console_CommandLine::parent to Console_CommandLine_Command
  • Access: public



[ Top ]

$renderer =  false

[line 146]

The command line parser renderer instance.
  • Var: implements Console_CommandLine_Renderer interface
  • Access: public

Type:   object that


[ Top ]

$subcommand_required =  false

[line 138]

Boolean that determine if providing a subcommand is mandatory.
  • Var: Whether a subcommand is required or not
  • Access: public

Type:   bool


[ Top ]

$version =  ''

[line 112]

A string that represents the version of the program, if this property is not empty and property add_version_option is not set to false, the command line parser will add a --version option, that will display the property content.
  • Access: public

Type:   string


[ Top ]



Method Detail

__construct (Constructor)   [line 298]

void __construct( [array $params = array()])

Constructor.

Example:

  1.  $parser = new Console_CommandLine(array(
  2.      'name'               => 'yourprogram'// defaults to argv[0]
  3.      'description'        => 'Description of your program',
  4.      'version'            => '0.0.1'// your program version
  5.      'add_help_option'    => true// or false to disable --help option
  6.      'add_version_option' => true// or false to disable --version option
  7.      'force_posix'        => false // or true to force posix compliance
  8.  ));

  • Access: public

Overridden in child classes as:

Console_CommandLine_Command::__construct()
Constructor.

Parameters:

array   $params   —  An optional array of parameters

[ Top ]

accept   [line 352]

void accept( mixed $instance)

Method to allow Console_CommandLine to accept either:

  • a custom renderer,
  • a custom outputter,
  • or a custom message provider

  • Throws: Console_CommandLine_Exception if wrong argument passed
  • Access: public

Parameters:

mixed   $instance   —  The custom instance

[ Top ]

addArgument   [line 477]

Console_CommandLine_Argument addArgument( mixed $name, [array $params = array()])

Adds an argument to the command line parser and returns it.

Adds an argument with the name $name and set its attributes with the array $params, then return the Console_CommandLine_Argument instance created. The method accepts another form: you can directly pass a Console_CommandLine_Argument object as the sole argument, this allows you to contruct the argument separately, in order to reuse it in different command line parsers or commands for example.

Example:

  1.  $parser = new Console_CommandLine();
  2.  // add an array argument
  3.  $parser->addArgument('input_files'array('multiple'=>true));
  4.  // add a simple argument
  5.  $parser->addArgument('output_file');
  6.  $result $parser->parse();
  7.  print_r($result->args['input_files']);
  8.  print_r($result->args['output_file']);
  9.  // will print:
  10.  // array('file1', 'file2')
  11.  // 'file3'
  12.  // if the command line was:
  13.  // myscript.php file1 file2 file3

In a terminal, the help will be displayed like this:

  1.  $ myscript.php install -h
  2.  Usage: myscript.php <input_files...> <output_file>


Parameters:

mixed   $name   —  A string containing the argument name or an instance of Console_CommandLine_Argument
array   $params   —  An array containing the argument attributes

[ Top ]

addBuiltinOptions   [line 1167]

void addBuiltinOptions( )

Adds the builtin "Help" and "Version" options if needed.
  • Access: public

[ Top ]

addCommand   [line 538]

Console_CommandLine_Command addCommand( mixed $name, [array $params = array()])

Adds a sub-command to the command line parser.

Adds a command with the given $name to the parser and returns the Console_CommandLine_Command instance, you can then populate the command with options, configure it, etc... like you would do for the main parser because the class Console_CommandLine_Command inherits from Console_CommandLine.

An example:

  1.  $parser = new Console_CommandLine();
  2.  $install_cmd $parser->addCommand('install');
  3.  $install_cmd->addOption(
  4.      'verbose',
  5.      array(
  6.          'short_name'  => '-v',
  7.          'long_name'   => '--verbose',
  8.          'description' => 'be noisy when installing stuff',
  9.          'action'      => 'StoreTrue'
  10.       )
  11.  );
  12.  $parser->parse();
Then in a terminal:
  1.  $ myscript.php install -h
  2.  Usage: myscript.php install [options]
  3.  
  4.  Options:
  5.    -h--help     display this help message and exit
  6.    -v--verbose  be noisy when installing stuff
  7.  
  8.  $ myscript.php install --verbose
  9.  Installing whatever...
  10.  $


Parameters:

mixed   $name   —  A string containing the command name or an instance of Console_CommandLine_Command
array   $params   —  An array containing the command attributes

[ Top ]

addOption   [line 626]

Console_CommandLine_Option addOption( mixed $name, [array $params = array()])

Adds an option to the command line parser and returns it.

Adds an option with the name $name and set its attributes with the array $params, then return the Console_CommandLine_Option instance created. The method accepts another form: you can directly pass a Console_CommandLine_Option object as the sole argument, this allows you to contruct the option separately, in order to reuse it in different command line parsers or commands for example.

Example:

  1.  $parser = new Console_CommandLine();
  2.  $parser->addOption('path'array(
  3.      'short_name'  => '-p',  // a short name
  4.      'long_name'   => '--path'// a long name
  5.      'description' => 'path to the dir'// a description msg
  6.      'action'      => 'StoreString',
  7.      'default'     => '/tmp' // a default value
  8.  ));
  9.  $parser->parse();

In a terminal, the help will be displayed like this:

  1.  $ myscript.php --help
  2.  Usage: myscript.php [options]
  3.  
  4.  Options:
  5.    -h--help  display this help message and exit
  6.    -p--path  path to the dir

Various methods to specify an option, these 3 commands are equivalent:

  1.  $ myscript.php --path=some/path
  2.  $ myscript.php -p some/path
  3.  $ myscript.php -psome/path


Parameters:

mixed   $name   —  A string containing the option name or an instance of Console_CommandLine_Option
array   $params   —  An array containing the option attributes

[ Top ]

displayError   [line 666]

void displayError( string $error, [int $exitCode = 1])

Displays an error to the user via stderr and exit with $exitCode if its value is not equals to false.
  • Access: public

Parameters:

string   $error   —  The error message
int   $exitCode   —  The exit code number (default: 1). If set to false, the exit() function will not be called

[ Top ]

displayUsage   [line 686]

void displayUsage( [int $exitCode = 0])

Displays the usage help message to the user via stdout and exit with $exitCode if its value is not equals to false.
  • Access: public

Parameters:

int   $exitCode   —  The exit code number (default: 0). If set to false, the exit() function will not be called

[ Top ]

displayVersion   [line 707]

void displayVersion( [int $exitCode = 0])

Displays the program version to the user via stdout and exit with $exitCode if its value is not equals to false.
  • Access: public

Parameters:

int   $exitCode   —  The exit code number (default: 0). If set to false, the exit() function will not be called

[ Top ]

findOption   [line 726]

mixed findOption( string $str)

Finds the option that matches the given short_name (ex: -v), long_name (ex: --verbose) or name (ex: verbose).
  • Return: A Console_CommandLine_Option instance or false
  • Access: public

Parameters:

string   $str   —  The option identifier

[ Top ]

fromXmlFile   [line 390]

Console_CommandLine fromXmlFile( string $file)

Returns a command line parser instance built from an xml file.

Example:

  1.  require_once 'Console/CommandLine.php';
  2.  $parser Console_CommandLine::fromXmlFile('path/to/file.xml');
  3.  $result $parser->parse();

  • Return: The parser instance
  • Access: public

Parameters:

string   $file   —  Path to the xml file

[ Top ]

fromXmlString   [line 427]

Console_CommandLine fromXmlString( string $string)

Returns a command line parser instance built from an xml string.

Example:

  1.  require_once 'Console/CommandLine.php';
  2.  $xmldata '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  3.  <command>
  4.    <description>Compress files</description>
  5.    <option name="quiet">
  6.      <short_name>-q</short_name>
  7.      <long_name>--quiet</long_name>
  8.      <description>be quiet when run</description>
  9.      <action>StoreTrue/action>
  10.    </option>
  11.    <argument name="files">
  12.      <description>a list of files</description>
  13.      <multiple>true</multiple>
  14.    </argument>
  15.  </command>';
  16.  $parser Console_CommandLine::fromXmlString($xmldata);
  17.  $result $parser->parse();

  • Return: The parser instance
  • Access: public

Parameters:

string   $string   —  The xml data

[ Top ]

getArgcArgv   [line 1205]

array getArgcArgv( )

Tries to return an array containing argc and argv, or trigger an error if it fails to get them.
  • Return: The argc/argv array
  • Throws: Console_CommandLine_Exception
  • Access: protected

[ Top ]

parse   [line 862]

Console_CommandLine_Result parse( [integer $userArgc = null], [array $userArgv = null])

Parses the command line arguments and returns a Console_CommandLine_Result instance.
  • Return: The result instance
  • Throws: Exception on user errors
  • Access: public

Parameters:

integer   $userArgc   —  Number of arguments (optional)
array   $userArgv   —  Array containing arguments (optional)

[ Top ]

parseToken   [line 996]

void parseToken( string $token, object $result, array &$args, int $argc)

Parses the command line token and modifies *by reference* the $options and $args arrays.
  • Throws: Exception on user errors
  • Access: protected

Parameters:

string   $token   —  The command line token to parse
object   $result   —  The Console_CommandLine_Result instance
array   &$args   —  The argv array
int   $argc   —  Number of lasting args

[ Top ]

registerAction   [line 813]

void registerAction( string $name, string $class)

Registers a custom action for the parser, an example:

  1.  // in this example we create a "range" action:
  2.  // the user will be able to enter something like:
  3.  // $ <program> -r 1,5
  4.  // and in the result we will have:
  5.  // $result->options['range']: array(1, 5)
  6.  
  7.  require_once 'Console/CommandLine.php';
  8.  require_once 'Console/CommandLine/Action.php';
  9.  
  10.  class ActionRange extends Console_CommandLine_Action
  11.  {
  12.      public function execute($value=false$params=array())
  13.      {
  14.          $range explode(','str_replace(' '''$value));
  15.          if (count($range!= 2{
  16.              throw new Exception(sprintf(
  17.                  'Option "%s" must be 2 integers separated by a comma',
  18.                  $this->option->name
  19.              ));
  20.          }
  21.          $this->setResult($range);
  22.      }
  23.  }
  24.  // then we can register our action
  25.  Console_CommandLine::registerAction('Range''ActionRange');
  26.  // and now our action is available !
  27.  $parser = new Console_CommandLine();
  28.  $parser->addOption('range'array(
  29.      'short_name'  => '-r',
  30.      'long_name'   => '--range',
  31.      'action'      => 'Range'// note our custom action
  32.      'description' => 'A range of two integers separated by a comma'
  33.  ));
  34.  // etc...

  • Access: public

Parameters:

string   $name   —  The name of the custom action
string   $class   —  The class name of the custom action

[ Top ]

triggerError   [line 838]

void triggerError( string $msgId, int $level, [array $params = array()])

A wrapper for programming errors triggering.
  • Todo: remove Console::triggerError() and use exceptions only
  • Access: public

Parameters:

string   $msgId   —  Identifier of the message
int   $level   —  The php error level
array   $params   —  An array of search=>replaces entries

[ Top ]


Documentation generated on Mon, 11 Mar 2019 15:51:31 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.