#!/usr/bin/php
<?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.18 2007/08/02 23:30:31 squiz Exp $
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

error_reporting(E_ALL | E_STRICT);
require_once 'PHP/CodeSniffer.php';

/**
 * Prints out the usage information for this script.
 *
 * @return void
 */
function PHP_CodeSniffer_printUsage()
{
    echo 'Usage: phpcs [-nlvi] [--report=<report>] [--standard=<standard>]'.PHP_EOL;
    echo '    [--generator=<generator>] [--extensions=<extensions>]'.PHP_EOL;
    echo '    [--ignore=<patterns>] <file> ...'.PHP_EOL;
    echo '        -n           Do not print warnings'.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 '        <generator>  The name of a doc genertor to use'.PHP_EOL;
    echo '                     (forces doc generation instead of checking)'.PHP_EOL;
    echo '        <report>     Print either the "full", "xml" or "summary" report'.PHP_EOL;
    exit();

}//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()


// First, we need to ensure there is at least one coding standard
// installed, or they will never be able to run this script.
$installedStandards = PHP_CodeSniffer::getInstalledStandards();
if (count($installedStandards) === 0) {
    echo 'ERROR: There are no coding standards installed.'.PHP_EOL;
    exit();
}


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

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();
            }

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

            if (substr($arg, 0, 9) === '--report=') {
                $report = substr($arg, 9);
                if ($report !== 'full' && $report !== 'xml' && $report !== 'summary') {
                    echo 'ERROR: Report type "'.$report.'" not known.'.PHP_EOL;
                    exit();
                }
            } 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=') {
                $ignored = explode(',', substr($arg, 9));
            } else if (substr($arg, 0, 12) === '--generator=') {
                $generator = substr($arg, 12);
            } else {
                echo 'ERROR: option "'.$arg.'" not known.'.PHP_EOL.PHP_EOL;
                PHP_CodeSniffer_printUsage();
            }
        } else {
            $switches = str_split($arg);
            foreach ($switches as $switch) {
                if ($switch === '-') {
                    continue;
                }

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

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

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

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

if (count($installedStandards) > 1) {
    if ($standard === null) {
        echo 'ERROR: You must supply the name of the coding standard to use.'.PHP_EOL.PHP_EOL;
        PHP_CodeSniffer_printUsage();
    }
} else {
    $standard = array_pop($installedStandards);
}

// 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();
}

$phpcs = new PHP_CodeSniffer($verbosity);

// 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 'summary':
    $numErrors = $phpcs->printErrorReportSummary($showWarnings);
    break;
default:
    $numErrors = $phpcs->printErrorReport($showWarnings);
    break;
}

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

?>
