[ Index ]
 

Code source de Typo3 4.1.3

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/t3lib/ -> class.t3lib_cli.php (source)

   1  <?php
   2  /***************************************************************
   3  *  Copyright notice
   4  *
   5  *  (c) 2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
   6  *  All rights reserved
   7  *
   8  *  This script is part of the TYPO3 project. The TYPO3 project is
   9  *  free software; you can redistribute it and/or modify
  10  *  it under the terms of the GNU General Public License as published by
  11  *  the Free Software Foundation; either version 2 of the License, or
  12  *  (at your option) any later version.
  13  *
  14  *  The GNU General Public License can be found at
  15  *  http://www.gnu.org/copyleft/gpl.html.
  16  *  A copy is found in the textfile GPL.txt and important notices to the license
  17  *  from the author is found in LICENSE.txt distributed with these scripts.
  18  *
  19  *
  20  *  This script is distributed in the hope that it will be useful,
  21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  23  *  GNU General Public License for more details.
  24  *
  25  *  This copyright notice MUST APPEAR in all copies of the script!
  26  ***************************************************************/
  27  /**
  28   * Contains base class for TYPO3 cli scripts
  29   *
  30   * @author    Kasper Skaarhoj <kasperYYYY@typo3.com>
  31   */
  32  /**
  33   * [CLASS/FUNCTION INDEX of SCRIPT]
  34   *
  35   *
  36   *
  37   *   60: class t3lib_cli
  38   *   83:     function t3lib_cli()
  39   *   96:     function cli_getArg($option,$argv)
  40   *  112:     function cli_getArgIndex()
  41   *  131:     function cli_keyboardInput()
  42   *  142:     function cli_keyboardInput_yes()
  43   *  154:     function cli_echo($string='',$force=FALSE)
  44   *  169:     function cli_help()
  45   *  207:     function cli_indent($str,$indent)
  46   *
  47   * TOTAL FUNCTIONS: 8
  48   * (This index is automatically created/updated by the extension "extdeveval")
  49   *
  50   */
  51  
  52  
  53  /**
  54   * TYPO3 cli script basis
  55   *
  56   * @author    Kasper Skaarhoj <kasperYYYY@typo3.com>
  57   * @package TYPO3
  58   * @subpackage t3lib
  59   */
  60  class t3lib_cli {
  61  
  62      var $cli_args = array();            // Command line arguments, exploded into key => value-array pairs
  63      var $cli_options = array(
  64          array('-s','Silent operation, will only output errors and important messages.'),
  65          array('--silent','Same as -s'),
  66          array('-ss','Super silent, will not even output errors or important messages.'),
  67      );
  68      var $cli_help = array(
  69              'name' => 'CLI base class (overwrite this...)',
  70              'synopsis' => '###OPTIONS###',
  71              'description' => 'Class with basic functionality for CLI scripts (overwrite this...)',
  72              'examples' => 'Give examples...',
  73              'options' => '',
  74              'license' => 'GNU GPL - free software!',
  75              'author' => '[Author name]',
  76          );
  77      var $stdin = NULL;    
  78  
  79  
  80      /**
  81       * Constructor
  82       * Make sure child classes also call this!
  83       *
  84       * @return    void
  85       */
  86  	function t3lib_cli()    {
  87              // Loads the cli_args array with command line arguments
  88          $this->cli_args = $this->cli_getArgIndex();
  89      }
  90  
  91      /**
  92       * Finds the arg token (like "-s") in argv and returns the rest of argv from that point on.
  93       * This should only be used in special cases since this->cli_args should already be prepared with an index of values!
  94       *
  95       * @param    string        Option string, eg. "-s"
  96       * @param    array        Input argv array
  97       * @return    array        Output argv array with all options AFTER the found option.
  98       */
  99  	function cli_getArgArray($option,$argv)    {
 100          while (count($argv) && strcmp($argv[0],$option))    {
 101              array_shift($argv);
 102          }
 103  
 104          if (!strcmp($argv[0],$option))    {
 105              array_shift($argv);
 106              return count($argv) ? $argv : array('');
 107          }
 108      }
 109  
 110      /**
 111       * Return true if option is found
 112       *
 113       * @param    string        Option string, eg. "-s"
 114       * @return    boolean        TRUE if option found
 115       */
 116  	function cli_isArg($option)    {
 117          return isset($this->cli_args[$option]);
 118      }
 119  
 120      /**
 121       * Return argument value
 122       *
 123       * @param    string        Option string, eg. "-s"
 124       * @param    integer        Value index, default is 0 (zero) = the first one...
 125       * @return    boolean        TRUE if option found
 126       */
 127  	function cli_argValue($option,$idx=0)    {
 128          return is_array($this->cli_args[$option]) ? $this->cli_args[$option][$idx] : '';
 129      }
 130  
 131      /**
 132       * Will parse "_SERVER[argv]" into an index of options and values
 133       * Argument names (eg. "-s") will be keys and values after (eg. "-s value1 value2 ..." or "-s=value1") will be in the array.
 134       * Array is empty if no values
 135       *
 136       * @return    array
 137       */
 138  	function cli_getArgIndex()    {
 139          $cli_options = array();
 140          $index = '_DEFAULT';
 141          foreach($_SERVER['argv'] as $token)    {
 142              if ($token{0}==='-')    {
 143                  list($index,$opt) = explode('=',$token,2);
 144                  if (isset($cli_options[$index]))    {
 145                      echo 'ERROR: Option '.$index.' was used twice!'.chr(10);
 146                      exit;
 147                  }
 148                  $cli_options[$index] = array();
 149                  if (isset($opt))    {
 150                      $cli_options[$index][] = $opt;
 151                  }
 152              } else {
 153                  $cli_options[$index][] = $token;
 154              }
 155          }
 156          return $cli_options;
 157      }
 158      
 159      /**
 160       * Validates if the input arguments in this->cli_args are all listed in this->cli_options and if not, will exit with an error.
 161       */
 162  	function cli_validateArgs() {
 163          $cli_args_copy = $this->cli_args;
 164          unset($cli_args_copy['_DEFAULT']);
 165          $allOptions = array();
 166  
 167          foreach($this->cli_options as $cfg)    {
 168              $allOptions[] = $cfg[0];
 169              $argSplit = t3lib_div::trimExplode(' ',$cfg[0],1);
 170              if (isset($cli_args_copy[$argSplit[0]]))    {
 171  
 172                  foreach($argSplit as $i => $v)    {
 173                      $ii=$i;
 174                      if ($i>0)    {
 175                          if (!isset($cli_args_copy[$argSplit[0]][$i-1]))    {
 176                              echo 'ERROR: Option "'.$argSplit[0].'" requires a value ("'.$v.'") on position '.$i.chr(10);
 177                              exit;
 178                          }
 179                      }
 180                  }
 181  
 182                  $ii++;
 183                  if (isset($cli_args_copy[$argSplit[0]][$ii-1]))    {
 184                      echo 'ERROR: Option "'.$argSplit[0].'" does not support a value on position '.$ii.chr(10);
 185                      exit;
 186                  }
 187                  
 188                  unset($cli_args_copy[$argSplit[0]]);
 189              }
 190          }
 191          
 192          if (count($cli_args_copy))    {
 193              echo wordwrap('ERROR: Option '.implode(',',array_keys($cli_args_copy)).' was unknown to this script!'.chr(10).'(Options are: '.implode(', ',$allOptions).')'.chr(10));
 194              exit;
 195          }
 196      }
 197  
 198      /**
 199       * Asks stdin for keyboard input and returns the line (after enter is pressed)
 200       *
 201       * @return    string
 202       */
 203  	function cli_keyboardInput()    {
 204          
 205              // Have to open the stdin stream only ONCE! otherwise I cannot read multiple lines from it... :
 206          if (!$this->stdin)    {
 207              $this->stdin = fopen('php://stdin', 'r');
 208          }
 209          
 210          while (FALSE == ($line = fgets($this->stdin,1000)))    {}
 211  
 212          return trim($line);
 213      }
 214  
 215      /**
 216       * Asks for Yes/No from shell and returns true if "y" or "yes" is found as input.
 217       *
 218       * @param    string        String to ask before...
 219       * @return    boolean        TRUE if "y" or "yes" is the input (case insensitive)
 220       */
 221  	function cli_keyboardInput_yes($msg='')    {
 222          echo $msg.' (Yes/No + return): ';    // ONLY makes sense to echo it out since we are awaiting keyboard input - that cannot be silenced...
 223          return t3lib_div::inList('y,yes',strtolower($this->cli_keyboardInput()));
 224      }
 225  
 226      /**
 227       * Echos strings to shell, but respective silent-modes
 228       *
 229       * @param    string        The string
 230       * @param    boolean        If string should be written even if -s is set (-ss will subdue it!)
 231       * @return    boolean        Returns TRUE if string was outputted.
 232       */
 233  	function cli_echo($string='',$force=FALSE)    {
 234          if (isset($this->cli_args['-ss'])) {
 235              // Nothing to do...
 236          } elseif (isset($this->cli_args['-s']) || isset($this->cli_args['--silent'])) {
 237              if ($force)    { echo $string; return TRUE; }
 238          } else { echo $string; return TRUE; }
 239  
 240          return FALSE;
 241      }
 242  
 243      /**
 244       * Prints help-output from ->cli_help array
 245       *
 246       * @return    void
 247       */
 248  	function cli_help()    {
 249          foreach($this->cli_help as $key => $value)    {
 250              $this->cli_echo(strtoupper($key).":\n");
 251              switch($key) {
 252                  case 'synopsis':
 253                      $optStr = '';
 254                      foreach ($this->cli_options as $v)    {
 255                          $optStr.=' ['.$v[0].']';
 256                      }
 257                      $this->cli_echo($this->cli_indent(str_replace('###OPTIONS###',trim($optStr),$value),4)."\n\n");
 258                  break;
 259                  case 'options':
 260                      $this->cli_echo($this->cli_indent($value,4)."\n");
 261  
 262                      $maxLen = 0;
 263                      foreach ($this->cli_options as $v)    {
 264                          if (strlen($v[0])>$maxLen)    $maxLen=strlen($v[0]);
 265                      }
 266  
 267                      foreach ($this->cli_options as $v)    {
 268                          $this->cli_echo($v[0].substr($this->cli_indent(rtrim($v[1].chr(10).$v[2]),$maxLen+4),strlen($v[0]))."\n");
 269                      }
 270                      $this->cli_echo("\n");
 271                  break;
 272                  default:
 273                      $this->cli_echo($this->cli_indent($value,4)."\n\n");
 274                  break;
 275              }
 276          }
 277      }
 278  
 279      /**
 280       * Indentation function for 75 char wide lines.
 281       *
 282       * @param    string        String to break and indent.
 283       * @param    integer        Number of space chars to indent.
 284       * @return    string        Result
 285       */
 286  	function cli_indent($str,$indent)    {
 287          $lines = explode(chr(10),wordwrap($str,75-$indent));
 288          $indentStr = str_pad('',$indent,' ');
 289          foreach($lines as $k => $v)    {
 290              $lines[$k] = $indentStr.$lines[$k];
 291          }
 292          return implode(chr(10),$lines);
 293      }
 294  }
 295  
 296  ?>


Généré le : Sun Nov 25 17:13:16 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics