Advertisement
Guest User

Untitled

a guest
Apr 14th, 2014
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.11 KB | None | 0 0
  1. <?php
  2. class Console
  3. {
  4.     public function __construct($argv)
  5.     {
  6.         $this->config = array_merge($this->config, $this->configure($argv));
  7.     }
  8.    
  9.     protected function configure($argv)
  10.     {
  11.         $config["exec"] = array_shift($argv);
  12.        
  13.         while (($key = array_shift($argv))) {
  14.             switch ($key{0}) {
  15.                 case "-":
  16.                     switch ($key{1}) {
  17.                         case "-":
  18.                             if (($dlim = strpos($key, "="))) {
  19.                                 $config[substr($key, 2, $dlim - 2)] = substr($key, $dlim + 1);
  20.                             } else
  21.                                 $config[substr($key, 2)] = array_shift($argv);
  22.                             break;
  23.                        
  24.                         default:
  25.                             $config["flags"][substr($key, 1)] = true;
  26.                     }
  27.                     break;
  28.             }
  29.         }
  30.        
  31.         return $config;
  32.     }
  33.    
  34.     protected function isFlagged($name)
  35.     {
  36.         if (!isset($this->flags[$name])) {
  37.             throw new \InvalidArgumentException("invalid flag requested {$name}");
  38.         }
  39.         return $this->flags[$name];
  40.     }
  41.    
  42.     protected function getConfig($name)
  43.     {
  44.         if (!isset($this->config[$name])) {
  45.             throw new \InvalidArgumentException("invalid configuration requested {$name}");
  46.         }
  47.         return $this->config[$name];
  48.     }
  49.    
  50.     public static function main($argv = array())
  51.     {
  52.         return new static($argv);
  53.     }
  54.    
  55.     protected $config = array("exec" => null, "flags" => array("default" => false));
  56. }
  57.  
  58. class My extends Console
  59. {
  60.     public function __construct($argv)
  61.     {
  62.         parent::__construct($argv);
  63.        
  64.         try {
  65.             $input  = $this->getConfig("input");
  66.             $output = $this->getConfig("output");
  67.             /* and so on */
  68.         }
  69.         catch (\InvalidArgumentException $error) {
  70.             printf("Command line configuration error:\n\t%s", (string) $error);
  71.         }
  72.     }
  73. }
  74.  
  75. return My::main($argv);
  76. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement