parse() public méthode

public parse ( array $argv ) : OptionResult | Option[]
$argv array
Résultat OptionResult | Option[]
Exemple #1
0
 function parse($argv)
 {
     $result = $this->parser->parse($argv);
     $opt = array();
     foreach ($result as $key => $spec) {
         $opt[$key] = $spec;
     }
     return $opt;
 }
Exemple #2
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");
 }
Exemple #3
0
 /**
  * 
  * @param array $argsList
  * @param type $aliveObject
  * @param string $action
  */
 private function getArgs(array &$argsList, $aliveObject, $action)
 {
     $listOptions = array();
     if (isset($aliveObject->options)) {
         $listOptions = $aliveObject->options;
     }
     $specs = new OptionCollection();
     foreach ($listOptions as $option => $spec) {
         if ($spec['type'] != 'boolean') {
             if ($spec['multiple']) {
                 $option .= '+';
             } else {
                 if ($spec['required']) {
                     $option .= ':';
                 } else {
                     $option .= '?';
                 }
             }
         }
         $specs->add($option, $spec['help'])->isa($spec['type']);
     }
     $parser = new OptionParser($specs);
     $parsedOptions = self::parseOptions($this->arguments, $parser);
     if (isset($aliveObject->objectName)) {
         $events = Di::getDefault()->get('events');
         $manageCommandOptionsEvent = new ManageCommandOptionsEvent($aliveObject->objectName, $action, $listOptions, $parsedOptions);
         $events->emit('core.manage.command.options', array($manageCommandOptionsEvent));
         $listOptions = $manageCommandOptionsEvent->getOptions();
         $aliveObject->options = $listOptions;
     }
     $listOptions = array_merge($listOptions, array('h|help' => array('help' => 'help', 'type' => 'boolean', 'functionParams' => '', "toTransform" => '', 'required' => false, 'defaultValue' => false)));
     $specs = new OptionCollection();
     foreach ($listOptions as $option => $spec) {
         if ($spec['type'] != 'boolean') {
             if ($spec['multiple']) {
                 $option .= '+';
             } else {
                 if ($spec['required']) {
                     $option .= ':';
                 } else {
                     $option .= '?';
                 }
             }
         }
         $specs->add($option, $spec['help'])->isa($spec['type']);
     }
     try {
         $parser = new OptionParser($specs);
         $optionsParsed = $parser->parse($this->arguments);
     } catch (RequireValueException $ex) {
         echo $ex->getMessage();
     }
     if ($optionsParsed->help) {
         $printer = new ConsoleOptionPrinter();
         echo $printer->render($specs);
         die;
     }
     unset($listOptions['h|help']);
     $this->manageConsoleParams($listOptions, $optionsParsed, $argsList);
 }
Exemple #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;
 }
Exemple #5
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.
     }
 }
 /**
  * @expectedException GetOptionKit\Exception\RequireValueException
  */
 public function testParseOptionRequireValueException()
 {
     $options = new OptionCollection();
     $options->add('name:=string', 'name');
     $parser = new OptionParser($options);
     $parser->parse(array('app', '--name'));
 }
Exemple #7
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();
}
Exemple #8
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);
 }