Example #1
0
 function execute($flavorName)
 {
     $logger = $this->getLogger();
     $formatter = $logger->getFormatter();
     $specs = new OptionSpecCollection();
     /* load flavor generator */
     $logger->info("Loading flavor {$flavorName}...");
     $loader = new Flavor\FlavorLoader();
     $flavor = $loader->load($flavorName);
     $generator = $flavor->getGenerator();
     $logger->info2("Inializing option specs...");
     $generator->options($specs);
     $generator->setLogger($this->getLogger());
     $deps = $generator->getDependencies();
     /*
     if( count($deps) )
         $logger->info("Dependencies: " . 
                 join(' ',array_keys($deps)) );
     */
     foreach ($deps as $depGenerator) {
         $depGenerator->logAction("dependency", get_class($depGenerator), 1);
         $args = $depGenerator->getOption()->getArguments();
         $this->runGenerator($depGenerator, $args);
     }
     /* use GetOptionKit to parse options from $args */
     $args = func_get_args();
     array_shift($args);
     $parser = new OptionParser($specs);
     $result = $parser->parse($args);
     /* pass rest arguments for generation */
     $generator->setOption($result);
     $logger->info("Running main generator...");
     $this->runGenerator($generator, $result->getArguments());
     $logger->info("Done");
 }
Example #2
0
 function parse($argv)
 {
     $result = $this->parser->parse($argv);
     $opt = array();
     foreach ($result as $key => $spec) {
         $opt[$key] = $spec;
     }
     return $opt;
 }
Example #3
0
 /**
  *
  * @param array $argv
  * @param OptionParser $parser
  * @return $result
  */
 public function parseOptions(array $argv, $parser)
 {
     $result = array();
     $argv = $parser->preprocessingArguments($argv);
     $len = count($argv);
     for ($i = 0; $i < $len; ++$i) {
         $arg = new Argument($argv[$i]);
         if (!$arg->isOption()) {
             continue;
         }
         $next = null;
         if ($i + 1 < count($argv)) {
             $next = new Argument($argv[$i + 1]);
         }
         $spec = $parser->specs->get($arg->getOptionName());
         if (!$spec) {
             continue;
         }
         if ($spec->isRequired()) {
             if (!$parser->foundRequireValue($spec, $arg, $next)) {
                 continue;
             }
             $parser->takeOptionValue($spec, $arg, $next);
             if ($next && !$next->anyOfOptions($parser->specs)) {
                 $result[$spec->getId()] = $next->arg;
                 $i++;
             }
         }
     }
     return $result;
 }
Example #4
0
 /**
  * Configures the parameters to be sent to each Task action
  *
  *  option configuration
  *  --------------------------------------------------------
  *  o|option         flag option (with boolean value true)
  *  option:          option requires a value
  *  option+          option with multiple values
  *  option?          option with optional values
  *  option:=string   option with type constraint of string
  *  option:=number   option with type constraint of number
  *  option:=file     option with type constraint of file
  *  option:=date     option with type constraint of date
  *  option:=boolean  option with type constraint of boolean
  *  o                single character only option
  *  option           long option name
  *
  * @param  array  $cmdDef
  * @return array
  */
 protected function parseArgs($argv, $cmdDef)
 {
     // Configure the command line definition
     $specs = new OptionCollection();
     foreach ($cmdDef['opts'] as $option => $help) {
         $specs->add($option, $help);
     }
     // Every program will have an auto-generated help
     $specs->add('h|help', 'display this help and exit');
     // Assign the command definition
     try {
         $parser = new OptionParser($specs);
     } catch (\Exception $e) {
         error_log("{$cmd}: The program has misconfigured options.");
         exit(1);
     }
     if (isset($argv[0]) && in_array($argv[0], ['--help', '-h'])) {
         throw new PrintHelpException($cmdDef, $specs);
     }
     // Use the options definition to parse the program arguments
     try {
         $result = $parser->parse($argv);
     } catch (RequireValueException $e) {
         throw new PrintHelpException($cmdDef, $specs, $e->getMessage(), 1);
     } catch (InvalidOptionException $e) {
         throw new PrintHelpException($cmdDef, $specs, $e->getMessage(), 1);
     } catch (\Exception $e) {
         throw new PrintHelpException($cmdDef, $specs, $e->getMessage(), 1);
     }
     // Ensure that the required arguments are supplied
     if (count($result->arguments) < count($cmdDef['args']['required'])) {
         throw new PrintHelpException($cmdDef, $specs, 'missing operand', 1);
     }
     // Clean arguments
     $args = array_map(function ($arg) {
         return $arg->arg;
     }, $result->arguments);
     // Clean options
     $opts = array_map(function ($opt) {
         return $opt->value;
     }, $result->keys);
     // The final result to be used in Tasks
     $params = ['args' => $args, 'opts' => $opts];
     return $params;
 }
 function __construct($specs = array())
 {
     parent::__construct($specs);
     $this->index = 1;
 }
Example #6
0
 /**
  * Get options.
  *
  * @since 150424 Initial release.
  *
  * @param bool       $extract Extract into an array after parsing?
  * @param array|null $args    Args to parse; default is `$GLOBALS['argv']`.
  *
  * @return array|OptionResult|Option[] Associative array, or the result set of Option objs.
  */
 public function parse(bool $extract = true, array $args = null)
 {
     $Parser = new OptionParser($this->OptionCollection);
     $OptionResult = $Options = $Parser->parse($args ?? $GLOBALS['argv']);
     if (!$extract) {
         // This contains some additional information for each option.
         return $OptionResult = $Options;
         // OptionResult|Option[]
     } else {
         $options = [];
         // Associative array (default behavior).
         foreach ($Options as $_key => $_Option) {
             $_key = preg_replace('/[^a-z0-9]/ui', '_', $_key);
             $_value = $_Option->getValue();
             $options[$_key] = $_value;
         }
         // unset($_key, $_value, $_Option);
         return $options;
         // Suitable for `extract()` now.
     }
 }
Example #7
0
 /**
  * @expectedException GetOptionKit\Exception\RequireValueException
  */
 public function testParseOptionRequireValueException()
 {
     $options = new OptionCollection();
     $options->add('name:=string', 'name');
     $parser = new OptionParser($options);
     $parser->parse(array('app', '--name'));
 }
 public function __construct(OptionCollection $specs)
 {
     parent::__construct($specs);
     $this->index = 1;
 }
Example #9
0
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('z|zoo?', 'option with optional value.')->isa('Boolean');
$specs->add('o|output?', 'option with optional value.')->isa('File')->defaultValue('output.txt');
// works for -vvv  => verbose = 3
$specs->add('v|verbose', 'verbose')->isa('Number')->incremental();
$specs->add('file:', 'option value should be a file.')->trigger(function ($value) {
    echo "Set value to :";
    var_dump($value);
})->isa('File');
$specs->add('r|regex:', 'with custom regex type value')->isa('Regex', '/^([a-z]+)$/');
$specs->add('d|debug', 'debug message.');
$specs->add('long', 'long option name only.');
$specs->add('s', 'short option name only.');
$specs->add('m', 'short option m');
$specs->add('4', 'short option with digit');
$printer = new ConsoleOptionPrinter();
echo $printer->render($specs);
$parser = new OptionParser($specs);
echo "Enabled options: \n";
try {
    $result = $parser->parse($argv);
    foreach ($result as $key => $spec) {
        echo $spec . "\n";
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
Example #10
0
 /**
  * @param array $argv Array of arguments passed to script
  * @example
  * ```php
  * $binary = new Binary([
  *     __FILE__,
  *     '-d',
  *     './tests/'
  * ]);
  *
  * $binary->invoke();
  * ```
  */
 public function __construct($argv)
 {
     $parser = new OptionParser(static::getArgumentSpecifications());
     $this->arguments = $parser->parse($argv);
     unset($parser);
 }