<?php
/**
 * Generic_Sniffs_PHP_SyntaxSniff.
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Blaine Schmeisser <blainesch@gmail.com>
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

/**
 * Generic_Sniffs_PHP_SyntaxSniff.
 *
 * Ensures PHP believes the syntax is clean.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Blaine Schmeisser <blainesch@gmail.com>
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: 1.5.5
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Generic_Sniffs_PHP_SyntaxSniff implements PHP_CodeSniffer_Sniff
{


    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(T_OPEN_TAG);

    }//end register()


    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                  $stackPtr  The position of the current token in
     *                                        the stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $phpPath = PHP_CodeSniffer::getConfigData('php_path');
        if ($phpPath === null) {
            return;
        }

        $fileName = $phpcsFile->getFilename();
        $cmd      = "$phpPath -l \"$fileName\" 2>&1";
        $output   = shell_exec($cmd);

        $matches = array();
        if (preg_match('/^.*error:(.*) in .* on line ([0-9]+)/', $output, $matches)) {
            $error = trim($matches[1]);
            $line  = (int) $matches[2];

            $tokens   = $phpcsFile->getTokens();
            $numLines = $tokens[($phpcsFile->numTokens - 1)]['line'];
            if ($line > $numLines) {
                $line = $numLines;
            }

            foreach ($tokens as $id => $token) {
                if ($token['line'] === $line) {
                    $phpcsFile->addError("PHP syntax error: $error", $id, 'PHPSyntax');
                    break;
                }
            }
        }

    }//end process()


}//end class

?>
