Get getopt ignore first argument

3

I'm creating a PHP CLI, and wanted to run something like this

php console.php comando -a foo -b bar -d

But with the function getopt I can not pass comando if not the buga function and I do not receive any of the other arguments. I need to set a default parameter to -c :

php console.php -c comando -a foo -b bar -d

Does anyone know of any method to "parse" the arguments ignoring the first?

PS: I also need to get the first argument, to know which command to execute.

Code: (github link)

public function run() {

  $command = $this->getCommand();

  if (is_null($command)) return FALSE;
  $optcll = $command->getOptionCollection();
  $opts = $optcll->dump();

  // LINHA QUE PEGO OS ARGUMENTOS DO COMANDO
  $args = getopt($opts['options'], $opts['longopts']);

  return $command->execute($this, $args);

}
    
asked by anonymous 30.08.2017 / 22:12

1 answer

3

I do not know if it meets your needs, but there's the docopt library for PHP.

With it, you simply write the documentation of your commands that the library is in charge of handling the entries, giving you an object with the information provided by the user. For example, considering your example, we could do:

<?php

$doc = <<<DOC
Descrição da aplicação.

Usage:
  console.php comando [-a A] [-b B] [-d]
  console.php (-h | --help)
  console.php --version

Options:
  -h --help     Exibe a mensagem de ajuda.
  --version     Exibe a versão.
  -a A          Valor de A.
  -b B          Valor de B.
  -d            Define como D.
DOC;

require('vendor/autoload.php');

$args = Docopt::handle($doc, array('version'=>'0.1.0'));

foreach ($args as $k => $v)
{
    echo $k.': '.json_encode($v).PHP_EOL;
}

Thus, you can display the help message with the command:

$ php console.php -h

Descrição da aplicação.

Usage:
  console.php comando [-a A] [-b B] [-d]
  console.php (-h | --help)
  console.php --version

Options:
  -h --help     Exibe a mensagem de ajuda.
  --version     Exibe a versão.
  -a A          Valor de A.
  -b B          Valor de B.
  -d            Define como D.

View the version with the command:

$ php console.php --version

0.1.0

Or run the commands provided in Usage :

$ php console.php comando

comando: true
-a: null
-b: null
-d: false
--help: false
--version: false

As I set the options as optional and did not report them, they are defined as% with_de% those that have value, such as null and -a , and as -b those that are flags , as false . When you enter the values, it is:

$ php console.php comando -a foo -b bar -d

comando: true
-a: "foo"
-b: "bar"
-d: true
--help: false
--version: false
    
02.09.2017 / 13:19