#!/usr/bin/php -Cq
<?php
    /**
    * Console script to use PHP_Beautifier from the command line
    *
    * Get more information using
    *
    * - php_beautifier --help (*nix)
    * - php_beautifier.bat --help (Windows)
    *
    * PHP version 5
    *
    * LICENSE: This source file is subject to version 3.0 of the PHP license
    * that is available through the world-wide-web at the following URI:
    * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
    * the PHP License and are unable to obtain it through the web, please
    * send a note to license@php.net so we can mail you a copy immediately.
    * @category   PHP
    * @package PHP_Beautifier
    * @author Claudio Bustos <clbustos@dotgeek.org>
    * @copyright  2004-2005 Claudio Bustos
    * @link     http://pear.php.net/package/PHP_Beautifier
    * @link     http://clbustos.dotgeek.org
    * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
    * @version    CVS: $Id:$
    */
    // First, test if the interpreter is the cli one
    if (php_sapi_name() != 'cli') {
        echo "You have to use php_beautifier with cli version of php. 
		If you only have the cgi version, see Beautifier.php to
		use this software within a script\n";
        exit();
    }
    /**
    * Require PEAR Class
    */
    require_once 'PEAR.php';
    /**
    * Require for PEAR Getopt class
    */
    require_once 'Console/Getopt.php';
    /**
    * Require for PEAR System class
    */
    require_once 'System.php';
    /**
    * Require the beautify_php class....
    */
    require_once 'PHP/Beautifier.php';
    /**
    * Require for PHP_Beautifier_Batch
    */
    require_once 'PHP/Beautifier/Batch.php';
    define('PHP_Beautifier_WINDOWS', substr(PHP_OS, 0, 3) == 'WIN');
    error_reporting(E_ALL);
    // get log object
    $oLog = PHP_Beautifier_Common::getLog();
    
    //default_options
    $aInputFiles = STDIN;
    $sOutputFile = STDOUT;
    $sIndentChar = ' ';
    $iIndentNumber = 4;
    $aFilters = array();
    $bRecursive = false;
    $sCompress = false;
    $aFiltersDirectory = array();
	$iVerbose=PEAR_LOG_WARNING;
    //end default_options
    $argv = Console_Getopt::readPHPArgv();
    $aLongOptions = array(
        'input=',
        'output=',
        'indent_tabs==',
        'indent_spaces==',
        'filters=',
        'directory_filters=',
        'recursive',
        'help',
        'compress==',
		'verbose'
    );
    $options = Console_Getopt::getopt($argv, "f:o:d:l:t::s::c::r?v", $aLongOptions);
    if (PEAR::isError($options)) {
        usage($options);
    }
    foreach($options[0] as $opt) {
        $sArgument = str_replace('-', '', $opt[0]);
        $sParam = $opt[1];
        $oLog->log("Arg: ".$sArgument."[$sParam]", PEAR_LOG_DEBUG);
        switch ($sArgument) {
            case 'input':
            case 'f':
                $aInputFiles = ($sParam == '-') ? STDIN : array(
                    $sParam
                );
            break;

            case 'output':
            case 'o':
                $sOutputFile = ($sParam == '-') ? STDOUT : $sParam;
            break;

            case 'indent_tabs':
            case 't':
                $sIndentChar = "\t";
                $iIndentNumber = ($sParam) ? (int)$sParam : 1;
            break;

            case 'indent_spaces':
            case 's':
                $sIndentChar = " ";
                $iIndentNumber = ($sParam) ? (int)$sParam : 4;
            break;

            case 'filters':
            case 'l':
                $aBruteFilters = explode(' ', $sParam);
                foreach($aBruteFilters as $sFilter) {
                    $sNombre = '';
                    preg_match("/([^(]*)(\((.*)\))*/", $sFilter, $aMatch);
                    $sFilterName = $aMatch[1];
                    $aFilterArgs = array();
                    if (!empty($aMatch[3])) {
                        $aSubArgs = explode(',', $aMatch[3]);
                        foreach($aSubArgs as $sSubArg) {
                            list($sKey, $sValue) = explode('=', $sSubArg);
                            $aFilterArgs[$sKey] = $sValue;
                        }
                    }
                    $aFilters[$sFilterName] = $aFilterArgs;
                }
            break;

            case 'directory_filters':
            case 'd':
                $sep = (PHP_Beautifier_WINDOWS) ? ';' : ':';
                $aFiltersDirectory = explode($sep, $sParam);
            break;

            case 'recursive':
            case 'r':
                $oLog->log('Recursive: on');
                $bRecursive = true;
            break;

            case 'compress':
            case 'c':
                $sCompress = ($sParam) ? $sParam : 'gz';
            break;

            case 'help':
            case '?':
                usage();
            break;
			case 'v':
			case 'verbose':
				$iVerbose=PEAR_LOG_INFO;
			break;
        }
    }
	// add the console logger
    $oLogConsole = Log::factory('console', '', 'php_beautifier', array(
        'stream'=>STDERR
    ) , $iVerbose);
    $oLog->addChild($oLogConsole);	
	
    if (!empty($options[1])) {
        $aFiles = $options[1];
        if (count($options[1]) == 1) {
            $aInputFiles = ($aFiles[0] == '-') ? STDIN : array(
                $aFiles[0]
            );
            $sOutputFile = STDOUT;
        } else {
            $aInputFiles = array_slice($aFiles, 0, count($aFiles) -1);
            $sOut = end($aFiles);
            $sOutputFile = ($sOut == '-') ? STDOUT : $sOut;
        }
    }
    $oLog->log("In :".@implode(',', $aInputFiles) , PEAR_LOG_INFO);
    $oLog->log("Out:".$sOutputFile, PEAR_LOG_INFO);
    $start = time();
    ini_set('max_execution_time', 0);
    // start script
    try {
        $oBeautSingle = new PHP_Beautifier();
        $oBeaut = new PHP_Beautifier_Batch($oBeautSingle);
        $oBeaut->setRecursive($bRecursive);
        $oBeaut->setInputFile($aInputFiles);
        $oBeaut->setOutputFile($sOutputFile);
        $oBeaut->setIndentChar($sIndentChar);
        $oBeaut->setIndentNumber($iIndentNumber);
        $oBeaut->setCompress($sCompress);
        if ($aFilters) {
            foreach($aFilters as $sName=>$aArgs) {
                $oBeaut->addFilter($sName, $aArgs);
            }
        }
        if ($aFiltersDirectory) {
            foreach($aFiltersDirectory as $sDirectory) {
                $oBeaut->addFilterDirectory($sDirectory);
            }
        }
        $oBeaut->process();
        $oBeaut->save();
        $sNameOut = ($sOutputFile == STDOUT) ? 'STDOUT' : $sOutputFile;
        $sNameIn = ($aInputFiles == STDIN) ? 'STDIN' : implode(',', $aInputFiles);
        // Log
        if ($aFilters) {
            $oLog->log("Filters used: ".implode(',', array_keys($aFilters)) , PEAR_LOG_INFO);
        }
        $oLog->log($sNameIn." to $sNameOut done");
        $oLog->log(round(time() -$start, 2) ." seconds needed\n");
    }
    catch(Exception $oExp) {
        $oLog->log($oExp->getMessage() , PEAR_LOG_ERR);
        $aBacktrace = $oExp->getTrace();
        foreach($aBacktrace as $iIndex=>$aTrace) {
            $oLog->log(sprintf("#%d %s(%d):%s%s%s()", $iIndex, $aTrace['file'], $aTrace['line'], @$aTrace['class'], @$aTrace['type'], $aTrace['function']) , PEAR_LOG_DEBUG);
        }
    }
    function usage($obj = null) 
    {
        if ($obj !== null) {
            fputs(STDERR, $obj->getMessage());
        }
        // php_beautifier->setBeautify(false)
        fputs(STDERR,
          "\nUsage: php_beautifier [options] <infile> <out>\n".
          "         <infile> and/or <out> can be '-', which means stdin/stdout.\n".
          "         you can use ? and * for batch processing\n".
          "         <out> can be a dir (ending with '/' or a real dir)\n". 
          "               or a file (without '/')\n".
          "         multiple ins and one out = merge all files in one output\n".
          "Options:\n".
          "     --input             or -f <file>    input file  - default: stdin\n".
          "     --output            or -o <out>     output dir or file - default: stdout\n".
          "     --indent_tabs       or -t <int>     indent with tabs\n".
          "     --indent_spaces     or -s <int>     indent with spaces - default\n".
          "     --filters           or -l <fil_def> Add filter(s)\n".
          "     --directory_filters or -d <path>    Include dirs for filters\n".
          "     --compress          or -c <type>    Compress output\n".
          "     --recursive         or -r           Search in subdir recursively\n".
          "     --help              or -?           display help/usage (this message)\n\n".
          "Filter definition:\n".
          "     --filters \"Filter1(setting1=value1,setting2=value2) Filter2()\"".
          "\n");
        // php_beautifier->setBeautify(true)
        exit;
    }
?>