#!"@php_bin@" -Cq
<?php
    /* vim: set expandtab tabstop=4 shiftwidth=4: */
    // +----------------------------------------------------------------------+
    // | PHP version 5                                                        |
    // +----------------------------------------------------------------------+
    // | Copyright (c) 1997-2004 The PHP Group                                |
    // +----------------------------------------------------------------------+
    // | This source file is subject to version 3.0 of the PHP license,       |
    // | that is bundled with this package in the file LICENSE, and is        |
    // | available through the world-wide-web at the following url:           |
    // | 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 world-wide-web, please send a note to          |
    // | license@php.net so we can mail you a copy immediately.               |
    // +----------------------------------------------------------------------+
    // | Authors: Claudio Bustos <cdx@users.sourceforge.net>                  |
    // |          Jens Bierkandt <schtorch@users.sourceforge.net>             |
    // +----------------------------------------------------------------------+
    //
    // $Id:
    /**
    * Console script to use PHP_Beautifier from the command line
    *
    * How to use:
    * - php_beautifier --help (*nix)
    * - php_beautifier.bat --help (Windows)
    *
    */
    /**
    * 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_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();
    // add the console logger
    $oLogConsole = Log::factory('console', '', 'php_beautifier', array(
        'stream'=>STDERR
    ) , PEAR_LOG_INFO);
    $oLog->addChild($oLogConsole);
    //default_options
    $aInputFiles = STDIN;
    $sOutputFile = STDOUT;
    $sIndentChar = ' ';
    $iIndentNumber = 4;
    $aFilters = array();
    $bRecursive = false;
    $sCompress = false;
    $aFiltersDirectory = array();
    //end default_options
    $argv = Console_Getopt::readPHPArgv();
    $aLongOptions = array(
        'input=',
        'output=',
        'indent_tabs==',
        'indent_spaces==',
        'filters=',
        'directory_filters=',
        'recursive',
        'help',
        'compress=='
    );
    $options = Console_Getopt::getopt($argv, "f:o:d:l:t::s::c::r?", $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':
                $bRecursive = true;
            break;

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

            case 'help':
            case '?':
                usage();
            break;
        }
    }
    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_DEBUG);
    $oLog->log("Out:".$sOutputFile, PEAR_LOG_DEBUG);
    $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);
        $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;
    }
?>