Skip to content

Parsing fails on option-arguments beginning with a hyphen

Created by: okdana

GetOpt doesn't properly support option-arguments that begin with a hyphen. Specifically, it only handles them as expected when they're part of the same word/argument as the option itself:

% composer require -q ulrichsg/getopt-php

% cat test.php
<?php

require_once __DIR__ . '/vendor/autoload.php';

$getopt = new \GetOpt\GetOpt([
  (new \GetOpt\Option('f', 'foo', \GetOpt\GetOpt::REQUIRED_ARGUMENT)),
]);

try {
  $getopt->parse();
  echo $getopt->getOption('foo'), "\n";
} catch ( \Exception $e ) {
  echo $e->getMessage(), "\n";
}

% php test.php -f-1
-1
% php test.php -f -1
Option 'foo' must have a value

% php test.php --foo=-1
-1
% php test.php --foo -1
Option 'foo' must have a value

Not sure if this is intended to catch mistakes or if it's just an oversight, but it's contrary to the way POSIX/GNU-style argument parsers normally work, and it breaks many common use cases like negative numbers and - as a short-hand for stdin/stdout. (Edit: Actually it does handle - correctly.)

If it is deliberate, could there be an option to disable it?