#!@php_bin@
<?php
/**
 * PHP_CodeSniffer tokenises PHP code and detects violations of a
 * defined set of coding standards.
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   CVS: $Id: phpcs,v 1.36 2008/01/08 22:05:59 squiz Exp $
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

// Check the PHP version.
if (version_compare(PHP_VERSION, '5.1.0') === -1) {
    echo 'ERROR: PHP_CodeSniffer requires PHP version 5.1.0 or greater.'.PHP_EOL;
    exit(2);
}

error_reporting(E_ALL | E_STRICT);

if (is_file(dirname(__FILE__).'/../CodeSniffer.php') === true) {
    include_once dirname(__FILE__).'/../CodeSniffer.php';
} else {
    include_once 'PHP/CodeSniffer.php';
}

/**
 * Prints out the usage information for this script.
 *
 * @return void
 */
function PHP_CodeSniffer_printUsage()
{
    echo 'Usage: phpcs [-nwlvi] [--report=<report>] [--standard=<standard>]'.PHP_EOL;
    echo '    [--config-set key value] [--config-delete key] [--config-show]'.PHP_EOL;
    echo '    [--generator=<generator>] [--extensions=<extensions>]'.PHP_EOL;
    echo '    [--ignore=<patterns>] [--tab-width=<width>] <file> ...'.PHP_EOL;
    echo '        -n           Do not print warnings'.PHP_EOL;
    echo '        -w           Print both warnings and errors (on by default)'.PHP_EOL;
    echo '        -l           Local directory only, no recursion'.PHP_EOL;
    echo '        -v[v][v]     Print verbose output'.PHP_EOL;
    echo '        -i           Show a list of installed coding standards'.PHP_EOL;
    echo '        --help       Print this help message'.PHP_EOL;
    echo '        --version    Print version information'.PHP_EOL;
    echo '        <file>       One or more files and/or directories to check'.PHP_EOL;
    echo '        <extensions> A comma separated list of file extensions to check'.PHP_EOL;
    echo '                     (only valid if checking a directory)'.PHP_EOL;
    echo '        <patterns>   A comma separated list of patterns that are used'.PHP_EOL;
    echo '                     to ignore directories and files'.PHP_EOL;
    echo '        <standard>   The name of the coding standard to use'.PHP_EOL;
    echo '        <width>      The number of spaces each tab represents'.PHP_EOL;
    echo '        <generator>  The name of a doc generator to use'.PHP_EOL;
    echo '                     (forces doc generation instead of checking)'.PHP_EOL;
    echo '        <report>     Print either the "full", "xml", "checkstyle",'.PHP_EOL;
    echo '                     "csv" or "summary" report'.PHP_EOL;
    echo '                     (the "full" report is printed by default)'.PHP_EOL;

}//end PHP_CodeSniffer_printUsage()


/**
 * Prints out a list of installed coding standards.
 *
 * @return void
 */
function PHP_CodeSniffer_printInstalledStandards()
{
    $installedStandards = PHP_CodeSniffer::getInstalledStandards();
    $numStandards       = count($installedStandards);

    if ($numStandards === 0) {
        echo 'No coding standards are installed.'.PHP_EOL;
    } else {
        $lastStandard = array_pop($installedStandards);
        if ($numStandards === 1) {
            echo 'The only coding standard installed is $lastStandard'.PHP_EOL;
        } else {
            $standardList  = implode(', ', $installedStandards);
            $standardList .= ' and '.$lastStandard;
            echo 'The installed coding standards are '.$standardList.PHP_EOL;
        }
    }

}//end PHP_CodeSniffer_printInstalledStandards()


// The default values for config settings.
$files      = array();
$standard   = null;
$verbosity  = 0;
$local      = false;
$extensions = array();
$ignored    = array();
$generator  = '';

$report = PHP_CodeSniffer::getConfigData('report_format');
if ($report === null) {
    $report = 'full';
}

$showWarnings = PHP_CodeSniffer::getConfigData('show_warnings');
if ($showWarnings === null) {
    $showWarnings = true;
} else {
    $showWarnings = (bool) $showWarnings;
}

$tabWidth = PHP_CodeSniffer::getConfigData('tab_width');
if ($tabWidth === null) {
    $tabWidth = 0;
} else {
    $tabWidth = (int) $tabWidth;
}

for ($i = 1; $i < $_SERVER['argc']; $i++) {
    $arg = $_SERVER['argv'][$i];
    if ($arg{0} === '-') {

        /*
            Check for all "--" switches first.
            Then check the "-" switches in one go.
        */

        if ($arg{1} === '-') {
            if ($arg === '--help') {
                PHP_CodeSniffer_printUsage();
                exit(0);
            }

            if ($arg === '--version') {
                echo 'PHP_CodeSniffer version @package_version@ (@package_state@) ';
                echo 'by Squiz Pty Ltd. (http://www.squiz.net)'.PHP_EOL;
                exit(0);
            }

            if ($arg === '--config-set') {
                $key   = $_SERVER['argv'][($i + 1)];
                $value = $_SERVER['argv'][($i + 2)];
                PHP_CodeSniffer::setConfigData($key, $value);
                exit(0);
            }

            if ($arg === '--config-delete') {
                $key = $_SERVER['argv'][($i + 1)];
                PHP_CodeSniffer::setConfigData($key, null);
                exit(0);
            }

            if ($arg === '--config-show') {
                $data = PHP_CodeSniffer::getAllConfigData();
                print_r($data);
                exit(0);
            }

            if (substr($arg, 0, 9) === '--report=') {
                $report = substr($arg, 9);
                $validReports = array('full', 'xml', 'checkstyle', 'csv', 'summary');
                if (in_array($report, $validReports) === false) {
                    echo 'ERROR: Report type "'.$report.'" not known.'.PHP_EOL;
                    exit(2);
                }
            } else if (substr($arg, 0, 11) === '--standard=') {
                $standard = substr($arg, 11);
            } else if (substr($arg, 0, 13) === '--extensions=') {
                $extensions = explode(',', substr($arg, 13));
            } else if (substr($arg, 0, 9) === '--ignore=') {
                // Split the ignore string on commas, unless the comma is escaped
                // using 1 or 3 slashes (\, or \\\,).
                $ignored = preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 9));
            } else if (substr($arg, 0, 12) === '--generator=') {
                $generator = substr($arg, 12);
            } else if (substr($arg, 0, 12) === '--tab-width=') {
                $tabWidth = (int) substr($arg, 12);
            } else {
                echo 'ERROR: option "'.$arg.'" not known.'.PHP_EOL.PHP_EOL;
                PHP_CodeSniffer_printUsage();
                exit(2);
            }
        } else {
            $switches = str_split($arg);
            foreach ($switches as $switch) {
                if ($switch === '-') {
                    continue;
                }

                switch ($switch) {
                case 'h':
                case '?':
                    PHP_CodeSniffer_printUsage();
                    exit(0);
                    break;
                case 'i' :
                    PHP_CodeSniffer_printInstalledStandards();
                    exit(0);
                    break;
                case 'v' :
                    $verbosity++;
                    break;
                case 'l' :
                    $local = true;
                    break;
                case 'n' :
                    $showWarnings = false;
                    break;
                case 'w' :
                    $showWarnings = true;
                    break;
                default:
                    echo 'ERROR: option "'.$switch.'" not known.'.PHP_EOL.PHP_EOL;
                    PHP_CodeSniffer_printUsage();
                    exit(2);
                }//end switch
            }//end foreach
        }//end else
    } else {
        // Assume everything that is not a switch is a file or directory.
        $files[] = realpath($arg);
    }
}//end for

if ($generator !== '') {
    $phpcs = new PHP_CodeSniffer($verbosity);
    $phpcs->generateDocs($standard, $files, $generator);
    exit(0);
}

if (empty($files) === true) {
    echo 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
    PHP_CodeSniffer_printUsage();
    exit(2);
}

foreach ($files as $file) {
    if (file_exists($file) === false) {
        echo 'ERROR: The file "'.$file.'" does not exist.'.PHP_EOL.PHP_EOL;
        PHP_CodeSniffer_printUsage();
        exit(2);
    }
}

if ($standard === null) {
    // They did not supply a standard to use.
    // Try to get the default from the config system.
    $standard = PHP_CodeSniffer::getConfigData('default_standard');
    if ($standard === null) {
        $standard = 'PEAR';
    }
}

// Check if the standard name is valid. If not, check that the case
// was not entered incorrectly before throwing an error.
if (PHP_CodeSniffer::isInstalledStandard($standard) === false) {
    $installedStandards = PHP_CodeSniffer::getInstalledStandards();
    foreach ($installedStandards as $validStandard) {
        if (strtolower($standard) === strtolower($validStandard)) {
            $standard = $validStandard;
            break;
        }
    }
}

if (PHP_CodeSniffer::isInstalledStandard($standard) === false) {
    // They didn't select a valid coding standard, so help them
    // out by letting them know which standards are installed.
    echo 'ERROR: the "'.$standard.'" coding standard is not installed. ';
    PHP_CodeSniffer_printInstalledStandards();
    exit(2);
}

$phpcs = new PHP_CodeSniffer($verbosity, $tabWidth);

// Set file extensions if they were specified. Otherwise,
// let PHP_CodeSniffer decide on the defaults.
if (empty($extensions) === false) {
    $phpcs->setAllowedFileExtensions($extensions);
}

// Set ignore patterns if they were specified.
if (empty($ignored) === false) {
    $phpcs->setIgnorePatterns($ignored);
}

$phpcs->process($files, $standard, array(), $local);
switch ($report) {
case 'xml':
    $numErrors = $phpcs->printXMLErrorReport($showWarnings);
    break;
case 'checkstyle':
    $numErrors = $phpcs->printCheckstyleErrorReport($showWarnings);
    break;
case 'csv':
    $numErrors = $phpcs->printCSVErrorReport($showWarnings);
    break;
case 'summary':
    $numErrors = $phpcs->printErrorReportSummary($showWarnings);
    break;
default:
    $numErrors = $phpcs->printErrorReport($showWarnings);
    break;
}

if ($numErrors === 0) {
    exit(0);
} else {
    exit(1);
}

?>
