Back to index

php5  5.3.10
gtCommandLineOptions.php
Go to the documentation of this file.
00001 <?php
00002 
00007 class gtCommandLineOptions {
00008 
00009   protected $shortOptions = array(
00010     'b',
00011     'e',
00012     'v',
00013     'h',
00014   );
00015 
00016   protected $shortOptionsWithArgs = array(
00017     'c',
00018     'm',
00019     'f',
00020     'i',
00021     's',
00022     'x',
00023     'k',
00024   );
00025   
00026   protected $options;
00027 
00028   protected function isShortOption($arg)
00029   {
00030     return (substr($arg, 0, 1) == '-') && (substr($arg, 1, 1) != '-');
00031   }
00032 
00033   public function isValidOptionArg($array, $index) {
00034     if (!isset($array[$index]))
00035     {
00036       return false;
00037     }
00038     return substr($array[$index], 0, 1) != '-';
00039   }
00040 
00041 
00042   public function parse($argv)
00043   {
00044     if(count($argv) < 2) {
00045       throw new gtMissingOptionsException('Command line options are required');
00046     }
00047     
00048     for ($i=1; $i<count($argv); $i++) {
00049 
00050       if ($this->isShortOption($argv[$i])) {
00051         $option = substr($argv[$i], 1);
00052       } else {
00053         throw new gtUnknownOptionException('Unrecognised command line option ' . $argv[$i]);
00054       }
00055 
00056       if (!in_array($option, array_merge($this->shortOptions, $this->shortOptionsWithArgs)))
00057       {
00058         throw new gtUnknownOptionException('Unknown option ' . $argv[$i]);
00059       }
00060 
00061       if (in_array($option, $this->shortOptions)) {
00062         $this->options[$option] = true;
00063         continue;
00064       }
00065 
00066       if (!$this->isValidOptionArg($argv, $i + 1))
00067       {
00068         throw new gtMissingArgumentException('Missing argument for command line option ' . $argv[$i]);
00069       }
00070 
00071       $i++;
00072       $this->options[$option] = $argv[$i];
00073     }
00074   }
00075   
00079   public function getOption($option)
00080   {
00081     if (!isset($this->options[$option])) {
00082       return false;
00083     }
00084     return $this->options[$option];
00085   }
00086 
00087 
00091   public function hasOption($option)
00092   {
00093     return isset($this->options[$option]);
00094   }
00095 
00096 
00097 }
00098 ?>