Chris@0: Chris@0: * @author Marc McIntyre Chris@0: * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) Chris@0: * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence Chris@0: * @link http://pear.php.net/package/PHP_CodeSniffer Chris@0: */ Chris@0: Chris@0: spl_autoload_register(array('PHP_CodeSniffer', 'autoload')); Chris@0: Chris@0: if (class_exists('PHP_CodeSniffer_Exception', true) === false) { Chris@0: throw new Exception('Class PHP_CodeSniffer_Exception not found'); Chris@0: } Chris@0: Chris@0: if (class_exists('PHP_CodeSniffer_File', true) === false) { Chris@0: throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_File not found'); Chris@0: } Chris@0: Chris@0: if (class_exists('PHP_CodeSniffer_Fixer', true) === false) { Chris@0: throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Fixer not found'); Chris@0: } Chris@0: Chris@0: if (class_exists('PHP_CodeSniffer_Tokens', true) === false) { Chris@0: throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Tokens not found'); Chris@0: } Chris@0: Chris@0: if (class_exists('PHP_CodeSniffer_CLI', true) === false) { Chris@0: throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_CLI not found'); Chris@0: } Chris@0: Chris@0: if (interface_exists('PHP_CodeSniffer_Sniff', true) === false) { Chris@0: throw new PHP_CodeSniffer_Exception('Interface PHP_CodeSniffer_Sniff not found'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * PHP_CodeSniffer tokenizes PHP code and detects violations of a Chris@0: * defined set of coding standards. Chris@0: * Chris@0: * Standards are specified by classes that implement the PHP_CodeSniffer_Sniff Chris@0: * interface. A sniff registers what token types it wishes to listen for, then Chris@0: * PHP_CodeSniffer encounters that token, the sniff is invoked and passed Chris@0: * information about where the token was found in the stack, and the token stack Chris@0: * itself. Chris@0: * Chris@0: * Sniff files and their containing class must be prefixed with Sniff, and Chris@0: * have an extension of .php. Chris@0: * Chris@0: * Multiple PHP_CodeSniffer operations can be performed by re-calling the Chris@0: * process function with different parameters. Chris@0: * Chris@0: * @category PHP Chris@0: * @package PHP_CodeSniffer Chris@0: * @author Greg Sherwood Chris@0: * @author Marc McIntyre Chris@0: * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) Chris@0: * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence Chris@0: * @version Release: @package_version@ Chris@0: * @link http://pear.php.net/package/PHP_CodeSniffer Chris@0: */ Chris@0: class PHP_CodeSniffer Chris@0: { Chris@0: Chris@0: /** Chris@0: * The current version. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: const VERSION = '2.8.1'; Chris@0: Chris@0: /** Chris@0: * Package stability; either stable, beta or alpha. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: const STABILITY = 'stable'; Chris@0: Chris@0: /** Chris@0: * The file or directory that is currently being processed. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $file = ''; Chris@0: Chris@0: /** Chris@0: * The directories that the processed rulesets are in. Chris@0: * Chris@0: * This is declared static because it is also used in the Chris@0: * autoloader to look for sniffs outside the PHPCS install. Chris@0: * This way, standards designed to be installed inside PHPCS can Chris@0: * also be used from outside the PHPCS Standards directory. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected static $rulesetDirs = array(); Chris@0: Chris@0: /** Chris@0: * The CLI object controlling the run. Chris@0: * Chris@0: * @var PHP_CodeSniffer_CLI Chris@0: */ Chris@0: public $cli = null; Chris@0: Chris@0: /** Chris@0: * The Reporting object controlling report generation. Chris@0: * Chris@0: * @var PHP_CodeSniffer_Reporting Chris@0: */ Chris@0: public $reporting = null; Chris@0: Chris@0: /** Chris@0: * An array of sniff objects that are being used to check files. Chris@0: * Chris@0: * @var array(PHP_CodeSniffer_Sniff) Chris@0: */ Chris@0: protected $listeners = array(); Chris@0: Chris@0: /** Chris@0: * An array of sniffs that are being used to check files. Chris@0: * Chris@0: * @var array(string) Chris@0: */ Chris@0: protected $sniffs = array(); Chris@0: Chris@0: /** Chris@0: * A mapping of sniff codes to fully qualified class names. Chris@0: * Chris@0: * The key is the sniff code and the value Chris@0: * is the fully qualified name of the sniff class. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: public $sniffCodes = array(); Chris@0: Chris@0: /** Chris@0: * The listeners array, indexed by token type. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: private $_tokenListeners = array(); Chris@0: Chris@0: /** Chris@0: * An array of rules from the ruleset.xml file. Chris@0: * Chris@0: * It may be empty, indicating that the ruleset does not override Chris@0: * any of the default sniff settings. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: protected $ruleset = array(); Chris@0: Chris@0: /** Chris@0: * An array of patterns to use for skipping files. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: protected $ignorePatterns = array(); Chris@0: Chris@0: /** Chris@0: * An array of extensions for files we will check. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: public $allowedFileExtensions = array(); Chris@0: Chris@0: /** Chris@0: * An array of default extensions and associated tokenizers. Chris@0: * Chris@0: * If no extensions are set, these will be used as the defaults. Chris@0: * If extensions are set, these will be used when the correct tokenizer Chris@0: * can not be determined, such as when checking a passed filename instead Chris@0: * of files in a directory. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: public $defaultFileExtensions = array( Chris@0: 'php' => 'PHP', Chris@0: 'inc' => 'PHP', Chris@0: 'js' => 'JS', Chris@0: 'css' => 'CSS', Chris@0: ); Chris@0: Chris@0: /** Chris@0: * An array of variable types for param/var we will check. Chris@0: * Chris@0: * @var array(string) Chris@0: */ Chris@0: public static $allowedTypes = array( Chris@0: 'array', Chris@0: 'boolean', Chris@0: 'float', Chris@0: 'integer', Chris@0: 'mixed', Chris@0: 'object', Chris@0: 'string', Chris@0: 'resource', Chris@0: 'callable', Chris@0: ); Chris@0: Chris@0: Chris@0: /** Chris@0: * Constructs a PHP_CodeSniffer object. Chris@0: * Chris@0: * @param int $verbosity The verbosity level. Chris@0: * 1: Print progress information. Chris@0: * 2: Print tokenizer debug information. Chris@0: * 3: Print sniff debug information. Chris@0: * @param int $tabWidth The number of spaces each tab represents. Chris@0: * If greater than zero, tabs will be replaced Chris@0: * by spaces before testing each file. Chris@0: * @param string $encoding The charset of the sniffed files. Chris@0: * This is important for some reports that output Chris@0: * with utf-8 encoding as you don't want it double Chris@0: * encoding messages. Chris@0: * @param bool $interactive If TRUE, will stop after each file with errors Chris@0: * and wait for user input. Chris@0: * Chris@0: * @see process() Chris@0: */ Chris@0: public function __construct( Chris@0: $verbosity=0, Chris@0: $tabWidth=0, Chris@0: $encoding='iso-8859-1', Chris@0: $interactive=false Chris@0: ) { Chris@0: if ($verbosity !== null) { Chris@0: $this->setVerbosity($verbosity); Chris@0: } Chris@0: Chris@0: if ($tabWidth !== null) { Chris@0: $this->setTabWidth($tabWidth); Chris@0: } Chris@0: Chris@0: if ($encoding !== null) { Chris@0: $this->setEncoding($encoding); Chris@0: } Chris@0: Chris@0: if ($interactive !== null) { Chris@0: $this->setInteractive($interactive); Chris@0: } Chris@0: Chris@0: if (defined('PHPCS_DEFAULT_ERROR_SEV') === false) { Chris@0: define('PHPCS_DEFAULT_ERROR_SEV', 5); Chris@0: } Chris@0: Chris@0: if (defined('PHPCS_DEFAULT_WARN_SEV') === false) { Chris@0: define('PHPCS_DEFAULT_WARN_SEV', 5); Chris@0: } Chris@0: Chris@0: if (defined('PHP_CODESNIFFER_CBF') === false) { Chris@0: define('PHP_CODESNIFFER_CBF', false); Chris@0: } Chris@0: Chris@0: // Set default CLI object in case someone is running us Chris@0: // without using the command line script. Chris@0: $this->cli = new PHP_CodeSniffer_CLI(); Chris@0: $this->cli->errorSeverity = PHPCS_DEFAULT_ERROR_SEV; Chris@0: $this->cli->warningSeverity = PHPCS_DEFAULT_WARN_SEV; Chris@0: $this->cli->dieOnUnknownArg = false; Chris@0: Chris@0: $this->reporting = new PHP_CodeSniffer_Reporting(); Chris@0: Chris@0: }//end __construct() Chris@0: Chris@0: Chris@0: /** Chris@0: * Autoload static method for loading classes and interfaces. Chris@0: * Chris@0: * @param string $className The name of the class or interface. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public static function autoload($className) Chris@0: { Chris@0: if (substr($className, 0, 4) === 'PHP_') { Chris@0: $newClassName = substr($className, 4); Chris@0: } else { Chris@0: $newClassName = $className; Chris@0: } Chris@0: Chris@0: $path = str_replace(array('_', '\\'), DIRECTORY_SEPARATOR, $newClassName).'.php'; Chris@0: Chris@0: if (is_file(dirname(__FILE__).DIRECTORY_SEPARATOR.$path) === true) { Chris@0: // Check standard file locations based on class name. Chris@0: include dirname(__FILE__).DIRECTORY_SEPARATOR.$path; Chris@0: return; Chris@0: } else { Chris@0: // Check for included sniffs. Chris@0: $installedPaths = PHP_CodeSniffer::getInstalledStandardPaths(); Chris@0: foreach ($installedPaths as $installedPath) { Chris@0: if (is_file($installedPath.DIRECTORY_SEPARATOR.$path) === true) { Chris@0: include $installedPath.DIRECTORY_SEPARATOR.$path; Chris@0: return; Chris@0: } Chris@0: } Chris@0: Chris@0: // Check standard file locations based on the loaded rulesets. Chris@0: foreach (self::$rulesetDirs as $rulesetDir) { Chris@0: if (is_file(dirname($rulesetDir).DIRECTORY_SEPARATOR.$path) === true) { Chris@0: include_once dirname($rulesetDir).DIRECTORY_SEPARATOR.$path; Chris@0: return; Chris@0: } Chris@0: } Chris@0: }//end if Chris@0: Chris@0: // Everything else. Chris@0: @include $path; Chris@0: Chris@0: }//end autoload() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets the verbosity level. Chris@0: * Chris@0: * @param int $verbosity The verbosity level. Chris@0: * 1: Print progress information. Chris@0: * 2: Print tokenizer debug information. Chris@0: * 3: Print sniff debug information. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setVerbosity($verbosity) Chris@0: { Chris@0: if (defined('PHP_CODESNIFFER_VERBOSITY') === false) { Chris@0: define('PHP_CODESNIFFER_VERBOSITY', $verbosity); Chris@0: } Chris@0: Chris@0: }//end setVerbosity() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets the tab width. Chris@0: * Chris@0: * @param int $tabWidth The number of spaces each tab represents. Chris@0: * If greater than zero, tabs will be replaced Chris@0: * by spaces before testing each file. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setTabWidth($tabWidth) Chris@0: { Chris@0: if (defined('PHP_CODESNIFFER_TAB_WIDTH') === false) { Chris@0: define('PHP_CODESNIFFER_TAB_WIDTH', $tabWidth); Chris@0: } Chris@0: Chris@0: }//end setTabWidth() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets the encoding. Chris@0: * Chris@0: * @param string $encoding The charset of the sniffed files. Chris@0: * This is important for some reports that output Chris@0: * with utf-8 encoding as you don't want it double Chris@0: * encoding messages. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setEncoding($encoding) Chris@0: { Chris@0: if (defined('PHP_CODESNIFFER_ENCODING') === false) { Chris@0: define('PHP_CODESNIFFER_ENCODING', $encoding); Chris@0: } Chris@0: Chris@0: }//end setEncoding() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets the interactive flag. Chris@0: * Chris@0: * @param bool $interactive If TRUE, will stop after each file with errors Chris@0: * and wait for user input. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setInteractive($interactive) Chris@0: { Chris@0: if (defined('PHP_CODESNIFFER_INTERACTIVE') === false) { Chris@0: define('PHP_CODESNIFFER_INTERACTIVE', $interactive); Chris@0: } Chris@0: Chris@0: }//end setInteractive() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets an array of file extensions that we will allow checking of. Chris@0: * Chris@0: * If the extension is one of the defaults, a specific tokenizer Chris@0: * will be used. Otherwise, the PHP tokenizer will be used for Chris@0: * all extensions passed. Chris@0: * Chris@0: * @param array $extensions An array of file extensions. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setAllowedFileExtensions(array $extensions) Chris@0: { Chris@0: $newExtensions = array(); Chris@0: foreach ($extensions as $ext) { Chris@0: $slash = strpos($ext, '/'); Chris@0: if ($slash !== false) { Chris@0: // They specified the tokenizer too. Chris@0: list($ext, $tokenizer) = explode('/', $ext); Chris@0: $newExtensions[$ext] = strtoupper($tokenizer); Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (isset($this->allowedFileExtensions[$ext]) === true) { Chris@0: $newExtensions[$ext] = $this->allowedFileExtensions[$ext]; Chris@0: } else if (isset($this->defaultFileExtensions[$ext]) === true) { Chris@0: $newExtensions[$ext] = $this->defaultFileExtensions[$ext]; Chris@0: } else { Chris@0: $newExtensions[$ext] = 'PHP'; Chris@0: } Chris@0: } Chris@0: Chris@0: $this->allowedFileExtensions = $newExtensions; Chris@0: Chris@0: }//end setAllowedFileExtensions() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets an array of ignore patterns that we use to skip files and folders. Chris@0: * Chris@0: * Patterns are not case sensitive. Chris@0: * Chris@0: * @param array $patterns An array of ignore patterns. The pattern is the key Chris@0: * and the value is either "absolute" or "relative", Chris@0: * depending on how the pattern should be applied to a Chris@0: * file path. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setIgnorePatterns(array $patterns) Chris@0: { Chris@0: $this->ignorePatterns = $patterns; Chris@0: Chris@0: }//end setIgnorePatterns() Chris@0: Chris@0: Chris@0: /** Chris@0: * Gets the array of ignore patterns. Chris@0: * Chris@0: * Optionally takes a listener to get ignore patterns specified Chris@0: * for that sniff only. Chris@0: * Chris@0: * @param string $listener The listener to get patterns for. If NULL, all Chris@0: * patterns are returned. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public function getIgnorePatterns($listener=null) Chris@0: { Chris@0: if ($listener === null) { Chris@0: return $this->ignorePatterns; Chris@0: } Chris@0: Chris@0: if (isset($this->ignorePatterns[$listener]) === true) { Chris@0: return $this->ignorePatterns[$listener]; Chris@0: } Chris@0: Chris@0: return array(); Chris@0: Chris@0: }//end getIgnorePatterns() Chris@0: Chris@0: Chris@0: /** Chris@0: * Sets the internal CLI object. Chris@0: * Chris@0: * @param object $cli The CLI object controlling the run. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setCli($cli) Chris@0: { Chris@0: $this->cli = $cli; Chris@0: Chris@0: }//end setCli() Chris@0: Chris@0: Chris@0: /** Chris@0: * Start a PHP_CodeSniffer run. Chris@0: * Chris@0: * @param string|array $files The files and directories to process. For Chris@0: * directories, each sub directory will also Chris@0: * be traversed for source files. Chris@0: * @param string|array $standards The set of code sniffs we are testing Chris@0: * against. Chris@0: * @param array $restrictions The sniff codes to restrict the Chris@0: * violations to. Chris@0: * @param boolean $local If true, don't recurse into directories. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function process($files, $standards, array $restrictions=array(), $local=false) Chris@0: { Chris@0: $files = (array) $files; Chris@0: $this->initStandard($standards, $restrictions); Chris@0: $this->processFiles($files, $local); Chris@0: Chris@0: }//end process() Chris@0: Chris@0: Chris@0: /** Chris@0: * Initialise the standard that the run will use. Chris@0: * Chris@0: * @param string|array $standards The set of code sniffs we are testing Chris@0: * against. Chris@0: * @param array $restrictions The sniff codes to restrict the testing to. Chris@0: * @param array $exclusions The sniff codes to exclude from testing. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function initStandard($standards, array $restrictions=array(), array $exclusions=array()) Chris@0: { Chris@0: $standards = (array) $standards; Chris@0: Chris@0: // Reset the members. Chris@0: $this->listeners = array(); Chris@0: $this->sniffs = array(); Chris@0: $this->ruleset = array(); Chris@0: $this->_tokenListeners = array(); Chris@0: self::$rulesetDirs = array(); Chris@0: Chris@0: // Ensure this option is enabled or else line endings will not always Chris@0: // be detected properly for files created on a Mac with the /r line ending. Chris@0: ini_set('auto_detect_line_endings', true); Chris@0: Chris@0: if (defined('PHP_CODESNIFFER_IN_TESTS') === true && empty($restrictions) === false) { Chris@0: // Should be one standard and one sniff being tested at a time. Chris@0: $installed = $this->getInstalledStandardPath($standards[0]); Chris@0: if ($installed !== null) { Chris@0: $standard = $installed; Chris@0: } else { Chris@0: $standard = self::realpath($standards[0]); Chris@0: if (is_dir($standard) === true Chris@0: && is_file(self::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml')) === true Chris@0: ) { Chris@0: $standard = self::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml'); Chris@0: } Chris@0: } Chris@0: Chris@0: $sniffs = $this->_expandRulesetReference($restrictions[0], dirname($standard)); Chris@0: } else { Chris@0: $sniffs = array(); Chris@0: foreach ($standards as $standard) { Chris@0: $installed = $this->getInstalledStandardPath($standard); Chris@0: if ($installed !== null) { Chris@0: $standard = $installed; Chris@0: } else { Chris@0: $standard = self::realpath($standard); Chris@0: if (is_dir($standard) === true Chris@0: && is_file(self::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml')) === true Chris@0: ) { Chris@0: $standard = self::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml'); Chris@0: } Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY === 1) { Chris@0: $ruleset = simplexml_load_string(file_get_contents($standard)); Chris@0: if ($ruleset !== false) { Chris@0: $standardName = (string) $ruleset['name']; Chris@0: } Chris@0: Chris@0: echo "Registering sniffs in the $standardName standard... "; Chris@0: if (count($standards) > 1 || PHP_CODESNIFFER_VERBOSITY > 2) { Chris@0: echo PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: $sniffs = array_merge($sniffs, $this->processRuleset($standard)); Chris@0: }//end foreach Chris@0: }//end if Chris@0: Chris@0: $sniffRestrictions = array(); Chris@0: foreach ($restrictions as $sniffCode) { Chris@0: $parts = explode('.', strtolower($sniffCode)); Chris@0: $sniffRestrictions[] = $parts[0].'_sniffs_'.$parts[1].'_'.$parts[2].'sniff'; Chris@0: } Chris@0: Chris@0: $sniffExclusions = array(); Chris@0: foreach ($exclusions as $sniffCode) { Chris@0: $parts = explode('.', strtolower($sniffCode)); Chris@0: $sniffExclusions[] = $parts[0].'_sniffs_'.$parts[1].'_'.$parts[2].'sniff'; Chris@0: } Chris@0: Chris@0: $this->registerSniffs($sniffs, $sniffRestrictions, $sniffExclusions); Chris@0: $this->populateTokenListeners(); Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY === 1) { Chris@0: $numSniffs = count($this->sniffs); Chris@0: echo "DONE ($numSniffs sniffs registered)".PHP_EOL; Chris@0: } Chris@0: Chris@0: }//end initStandard() Chris@0: Chris@0: Chris@0: /** Chris@0: * Processes the files/directories that PHP_CodeSniffer was constructed with. Chris@0: * Chris@0: * @param string|array $files The files and directories to process. For Chris@0: * directories, each sub directory will also Chris@0: * be traversed for source files. Chris@0: * @param boolean $local If true, don't recurse into directories. Chris@0: * Chris@0: * @return void Chris@0: * @throws PHP_CodeSniffer_Exception If files are invalid. Chris@0: */ Chris@0: public function processFiles($files, $local=false) Chris@0: { Chris@0: $files = (array) $files; Chris@0: $cliValues = $this->cli->getCommandLineValues(); Chris@0: $showProgress = $cliValues['showProgress']; Chris@0: $useColors = $cliValues['colors']; Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0) { Chris@0: echo 'Creating file list... '; Chris@0: } Chris@0: Chris@0: if (empty($this->allowedFileExtensions) === true) { Chris@0: $this->allowedFileExtensions = $this->defaultFileExtensions; Chris@0: } Chris@0: Chris@0: $todo = $this->getFilesToProcess($files, $local); Chris@0: $numFiles = count($todo); Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0) { Chris@0: echo "DONE ($numFiles files in queue)".PHP_EOL; Chris@0: } Chris@0: Chris@0: $numProcessed = 0; Chris@0: $dots = 0; Chris@0: $maxLength = strlen($numFiles); Chris@0: $lastDir = ''; Chris@0: foreach ($todo as $file) { Chris@0: $this->file = $file; Chris@0: $currDir = dirname($file); Chris@0: if ($lastDir !== $currDir) { Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0 || PHP_CODESNIFFER_CBF === true) { Chris@0: echo 'Changing into directory '.$currDir.PHP_EOL; Chris@0: } Chris@0: Chris@0: $lastDir = $currDir; Chris@0: } Chris@0: Chris@0: $phpcsFile = $this->processFile($file, null); Chris@0: $numProcessed++; Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0 Chris@0: || PHP_CODESNIFFER_INTERACTIVE === true Chris@0: || $showProgress === false Chris@0: ) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // Show progress information. Chris@0: if ($phpcsFile === null) { Chris@0: echo 'S'; Chris@0: } else { Chris@0: $errors = $phpcsFile->getErrorCount(); Chris@0: $warnings = $phpcsFile->getWarningCount(); Chris@0: if ($errors > 0) { Chris@0: if ($useColors === true) { Chris@0: echo "\033[31m"; Chris@0: } Chris@0: Chris@0: echo 'E'; Chris@0: } else if ($warnings > 0) { Chris@0: if ($useColors === true) { Chris@0: echo "\033[33m"; Chris@0: } Chris@0: Chris@0: echo 'W'; Chris@0: } else { Chris@0: echo '.'; Chris@0: } Chris@0: Chris@0: if ($useColors === true) { Chris@0: echo "\033[0m"; Chris@0: } Chris@0: }//end if Chris@0: Chris@0: $dots++; Chris@0: if ($dots === 60) { Chris@0: $padding = ($maxLength - strlen($numProcessed)); Chris@0: echo str_repeat(' ', $padding); Chris@0: $percent = round(($numProcessed / $numFiles) * 100); Chris@0: echo " $numProcessed / $numFiles ($percent%)".PHP_EOL; Chris@0: $dots = 0; Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY === 0 Chris@0: && PHP_CODESNIFFER_INTERACTIVE === false Chris@0: && $showProgress === true Chris@0: ) { Chris@0: echo PHP_EOL.PHP_EOL; Chris@0: } Chris@0: Chris@0: }//end processFiles() Chris@0: Chris@0: Chris@0: /** Chris@0: * Processes a single ruleset and returns a list of the sniffs it represents. Chris@0: * Chris@0: * Rules founds within the ruleset are processed immediately, but sniff classes Chris@0: * are not registered by this method. Chris@0: * Chris@0: * @param string $rulesetPath The path to a ruleset XML file. Chris@0: * @param int $depth How many nested processing steps we are in. This Chris@0: * is only used for debug output. Chris@0: * Chris@0: * @return array Chris@0: * @throws PHP_CodeSniffer_Exception If the ruleset path is invalid. Chris@0: */ Chris@0: public function processRuleset($rulesetPath, $depth=0) Chris@0: { Chris@0: $rulesetPath = self::realpath($rulesetPath); Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "Processing ruleset $rulesetPath".PHP_EOL; Chris@0: } Chris@0: Chris@0: $ruleset = simplexml_load_string(file_get_contents($rulesetPath)); Chris@0: if ($ruleset === false) { Chris@0: throw new PHP_CodeSniffer_Exception("Ruleset $rulesetPath is not valid"); Chris@0: } Chris@0: Chris@0: $ownSniffs = array(); Chris@0: $includedSniffs = array(); Chris@0: $excludedSniffs = array(); Chris@0: $cliValues = $this->cli->getCommandLineValues(); Chris@0: Chris@0: $rulesetDir = dirname($rulesetPath); Chris@0: self::$rulesetDirs[] = $rulesetDir; Chris@0: Chris@0: if (is_dir($rulesetDir.DIRECTORY_SEPARATOR.'Sniffs') === true) { Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\tAdding sniff files from \"/.../".basename($rulesetDir)."/Sniffs/\" directory".PHP_EOL; Chris@0: } Chris@0: Chris@0: $ownSniffs = $this->_expandSniffDirectory($rulesetDir.DIRECTORY_SEPARATOR.'Sniffs', $depth); Chris@0: } Chris@0: Chris@0: // Process custom sniff config settings. Chris@0: foreach ($ruleset->{'config'} as $config) { Chris@0: if ($this->_shouldProcessElement($config) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $this->setConfigData((string) $config['name'], (string) $config['value'], true); Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t=> set config value ".(string) $config['name'].': '.(string) $config['value'].PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: foreach ($ruleset->rule as $rule) { Chris@0: if (isset($rule['ref']) === false Chris@0: || $this->_shouldProcessElement($rule) === false Chris@0: ) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\tProcessing rule \"".$rule['ref'].'"'.PHP_EOL; Chris@0: } Chris@0: Chris@0: $includedSniffs = array_merge( Chris@0: $includedSniffs, Chris@0: $this->_expandRulesetReference($rule['ref'], $rulesetDir, $depth) Chris@0: ); Chris@0: Chris@0: if (isset($rule->exclude) === true) { Chris@0: foreach ($rule->exclude as $exclude) { Chris@0: if ($this->_shouldProcessElement($exclude) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\tExcluding rule \"".$exclude['name'].'"'.PHP_EOL; Chris@0: } Chris@0: Chris@0: // Check if a single code is being excluded, which is a shortcut Chris@0: // for setting the severity of the message to 0. Chris@0: $parts = explode('.', $exclude['name']); Chris@0: if (count($parts) === 4) { Chris@0: $this->ruleset[(string) $exclude['name']]['severity'] = 0; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> severity set to 0".PHP_EOL; Chris@0: } Chris@0: } else { Chris@0: $excludedSniffs = array_merge( Chris@0: $excludedSniffs, Chris@0: $this->_expandRulesetReference($exclude['name'], $rulesetDir, ($depth + 1)) Chris@0: ); Chris@0: } Chris@0: }//end foreach Chris@0: }//end if Chris@0: Chris@0: $this->_processRule($rule, $depth); Chris@0: }//end foreach Chris@0: Chris@0: // Process custom command line arguments. Chris@0: $cliArgs = array(); Chris@0: foreach ($ruleset->{'arg'} as $arg) { Chris@0: if ($this->_shouldProcessElement($arg) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (isset($arg['name']) === true) { Chris@0: $argString = '--'.(string) $arg['name']; Chris@0: if (isset($arg['value']) === true) { Chris@0: $argString .= '='.(string) $arg['value']; Chris@0: } Chris@0: } else { Chris@0: $argString = '-'.(string) $arg['value']; Chris@0: } Chris@0: Chris@0: $cliArgs[] = $argString; Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t=> set command line value $argString".PHP_EOL; Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: // Set custom php ini values as CLI args. Chris@0: foreach ($ruleset->{'ini'} as $arg) { Chris@0: if ($this->_shouldProcessElement($arg) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (isset($arg['name']) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $name = (string) $arg['name']; Chris@0: $argString = $name; Chris@0: if (isset($arg['value']) === true) { Chris@0: $value = (string) $arg['value']; Chris@0: $argString .= "=$value"; Chris@0: } else { Chris@0: $value = 'true'; Chris@0: } Chris@0: Chris@0: $cliArgs[] = '-d'; Chris@0: $cliArgs[] = $argString; Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t=> set PHP ini value $name to $value".PHP_EOL; Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: if (empty($cliValues['files']) === true && $cliValues['stdin'] === null) { Chris@0: // Process hard-coded file paths. Chris@0: foreach ($ruleset->{'file'} as $file) { Chris@0: $file = (string) $file; Chris@0: $cliArgs[] = $file; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t=> added \"$file\" to the file list".PHP_EOL; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: if (empty($cliArgs) === false) { Chris@0: // Change the directory so all relative paths are worked Chris@0: // out based on the location of the ruleset instead of Chris@0: // the location of the user. Chris@0: $inPhar = self::isPharFile($rulesetDir); Chris@0: if ($inPhar === false) { Chris@0: $currentDir = getcwd(); Chris@0: chdir($rulesetDir); Chris@0: } Chris@0: Chris@0: $this->cli->setCommandLineValues($cliArgs); Chris@0: Chris@0: if ($inPhar === false) { Chris@0: chdir($currentDir); Chris@0: } Chris@0: } Chris@0: Chris@0: // Process custom ignore pattern rules. Chris@0: foreach ($ruleset->{'exclude-pattern'} as $pattern) { Chris@0: if ($this->_shouldProcessElement($pattern) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (isset($pattern['type']) === false) { Chris@0: $pattern['type'] = 'absolute'; Chris@0: } Chris@0: Chris@0: $this->ignorePatterns[(string) $pattern] = (string) $pattern['type']; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t=> added global ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: $includedSniffs = array_unique(array_merge($ownSniffs, $includedSniffs)); Chris@0: $excludedSniffs = array_unique($excludedSniffs); Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: $included = count($includedSniffs); Chris@0: $excluded = count($excludedSniffs); Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "=> Ruleset processing complete; included $included sniffs and excluded $excluded".PHP_EOL; Chris@0: } Chris@0: Chris@0: // Merge our own sniff list with our externally included Chris@0: // sniff list, but filter out any excluded sniffs. Chris@0: $files = array(); Chris@0: foreach ($includedSniffs as $sniff) { Chris@0: if (in_array($sniff, $excludedSniffs) === true) { Chris@0: continue; Chris@0: } else { Chris@0: $files[] = self::realpath($sniff); Chris@0: } Chris@0: } Chris@0: Chris@0: return $files; Chris@0: Chris@0: }//end processRuleset() Chris@0: Chris@0: Chris@0: /** Chris@0: * Expands a directory into a list of sniff files within. Chris@0: * Chris@0: * @param string $directory The path to a directory. Chris@0: * @param int $depth How many nested processing steps we are in. This Chris@0: * is only used for debug output. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: private function _expandSniffDirectory($directory, $depth=0) Chris@0: { Chris@0: $sniffs = array(); Chris@0: Chris@0: if (defined('RecursiveDirectoryIterator::FOLLOW_SYMLINKS') === true) { Chris@0: $rdi = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::FOLLOW_SYMLINKS); Chris@0: } else { Chris@0: $rdi = new RecursiveDirectoryIterator($directory); Chris@0: } Chris@0: Chris@0: $di = new RecursiveIteratorIterator($rdi, 0, RecursiveIteratorIterator::CATCH_GET_CHILD); Chris@0: Chris@0: $dirLen = strlen($directory); Chris@0: Chris@0: foreach ($di as $file) { Chris@0: $filename = $file->getFilename(); Chris@0: Chris@0: // Skip hidden files. Chris@0: if (substr($filename, 0, 1) === '.') { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // We are only interested in PHP and sniff files. Chris@0: $fileParts = explode('.', $filename); Chris@0: if (array_pop($fileParts) !== 'php') { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $basename = basename($filename, '.php'); Chris@0: if (substr($basename, -5) !== 'Sniff') { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $path = $file->getPathname(); Chris@0: Chris@0: // Skip files in hidden directories within the Sniffs directory of this Chris@0: // standard. We use the offset with strpos() to allow hidden directories Chris@0: // before, valid example: Chris@0: // /home/foo/.composer/vendor/drupal/coder/coder_sniffer/Drupal/Sniffs/... Chris@0: if (strpos($path, DIRECTORY_SEPARATOR.'.', $dirLen) !== false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> $path".PHP_EOL; Chris@0: } Chris@0: Chris@0: $sniffs[] = $path; Chris@0: }//end foreach Chris@0: Chris@0: return $sniffs; Chris@0: Chris@0: }//end _expandSniffDirectory() Chris@0: Chris@0: Chris@0: /** Chris@0: * Expands a ruleset reference into a list of sniff files. Chris@0: * Chris@0: * @param string $ref The reference from the ruleset XML file. Chris@0: * @param string $rulesetDir The directory of the ruleset XML file, used to Chris@0: * evaluate relative paths. Chris@0: * @param int $depth How many nested processing steps we are in. This Chris@0: * is only used for debug output. Chris@0: * Chris@0: * @return array Chris@0: * @throws PHP_CodeSniffer_Exception If the reference is invalid. Chris@0: */ Chris@0: private function _expandRulesetReference($ref, $rulesetDir, $depth=0) Chris@0: { Chris@0: // Ignore internal sniffs codes as they are used to only Chris@0: // hide and change internal messages. Chris@0: if (substr($ref, 0, 9) === 'Internal.') { Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t* ignoring internal sniff code *".PHP_EOL; Chris@0: } Chris@0: Chris@0: return array(); Chris@0: } Chris@0: Chris@0: // As sniffs can't begin with a full stop, assume references in Chris@0: // this format are relative paths and attempt to convert them Chris@0: // to absolute paths. If this fails, let the reference run through Chris@0: // the normal checks and have it fail as normal. Chris@0: if (substr($ref, 0, 1) === '.') { Chris@0: $realpath = self::realpath($rulesetDir.'/'.$ref); Chris@0: if ($realpath !== false) { Chris@0: $ref = $realpath; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> $ref".PHP_EOL; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // As sniffs can't begin with a tilde, assume references in Chris@0: // this format at relative to the user's home directory. Chris@0: if (substr($ref, 0, 2) === '~/') { Chris@0: $realpath = self::realpath($ref); Chris@0: if ($realpath !== false) { Chris@0: $ref = $realpath; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> $ref".PHP_EOL; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: if (is_file($ref) === true) { Chris@0: if (substr($ref, -9) === 'Sniff.php') { Chris@0: // A single external sniff. Chris@0: self::$rulesetDirs[] = dirname(dirname(dirname($ref))); Chris@0: return array($ref); Chris@0: } Chris@0: } else { Chris@0: // See if this is a whole standard being referenced. Chris@0: $path = $this->getInstalledStandardPath($ref); Chris@0: if (self::isPharFile($path) === true && strpos($path, 'ruleset.xml') === false) { Chris@0: // If the ruleset exists inside the phar file, use it. Chris@0: if (file_exists($path.DIRECTORY_SEPARATOR.'ruleset.xml') === true) { Chris@0: $path = $path.DIRECTORY_SEPARATOR.'ruleset.xml'; Chris@0: } else { Chris@0: $path = null; Chris@0: } Chris@0: } Chris@0: Chris@0: if ($path !== null) { Chris@0: $ref = $path; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> $ref".PHP_EOL; Chris@0: } Chris@0: } else if (is_dir($ref) === false) { Chris@0: // Work out the sniff path. Chris@0: $sepPos = strpos($ref, DIRECTORY_SEPARATOR); Chris@0: if ($sepPos !== false) { Chris@0: $stdName = substr($ref, 0, $sepPos); Chris@0: $path = substr($ref, $sepPos); Chris@0: } else { Chris@0: $parts = explode('.', $ref); Chris@0: $stdName = $parts[0]; Chris@0: if (count($parts) === 1) { Chris@0: // A whole standard? Chris@0: $path = ''; Chris@0: } else if (count($parts) === 2) { Chris@0: // A directory of sniffs? Chris@0: $path = DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$parts[1]; Chris@0: } else { Chris@0: // A single sniff? Chris@0: $path = DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$parts[1].DIRECTORY_SEPARATOR.$parts[2].'Sniff.php'; Chris@0: } Chris@0: } Chris@0: Chris@0: $newRef = false; Chris@0: $stdPath = $this->getInstalledStandardPath($stdName); Chris@0: if ($stdPath !== null && $path !== '') { Chris@0: if (self::isPharFile($stdPath) === true Chris@0: && strpos($stdPath, 'ruleset.xml') === false Chris@0: ) { Chris@0: // Phar files can only return the directory, Chris@0: // since ruleset can be omitted if building one standard. Chris@0: $newRef = self::realpath($stdPath.$path); Chris@0: } else { Chris@0: $newRef = self::realpath(dirname($stdPath).$path); Chris@0: } Chris@0: } Chris@0: Chris@0: if ($newRef === false) { Chris@0: // The sniff is not locally installed, so check if it is being Chris@0: // referenced as a remote sniff outside the install. We do this Chris@0: // by looking through all directories where we have found ruleset Chris@0: // files before, looking for ones for this particular standard, Chris@0: // and seeing if it is in there. Chris@0: foreach (self::$rulesetDirs as $dir) { Chris@0: if (strtolower(basename($dir)) !== strtolower($stdName)) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $newRef = self::realpath($dir.$path); Chris@0: Chris@0: if ($newRef !== false) { Chris@0: $ref = $newRef; Chris@0: } Chris@0: } Chris@0: } else { Chris@0: $ref = $newRef; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> $ref".PHP_EOL; Chris@0: } Chris@0: }//end if Chris@0: }//end if Chris@0: Chris@0: if (is_dir($ref) === true) { Chris@0: if (is_file($ref.DIRECTORY_SEPARATOR.'ruleset.xml') === true) { Chris@0: // We are referencing an external coding standard. Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t* rule is referencing a standard using directory name; processing *".PHP_EOL; Chris@0: } Chris@0: Chris@0: return $this->processRuleset($ref.DIRECTORY_SEPARATOR.'ruleset.xml', ($depth + 2)); Chris@0: } else { Chris@0: // We are referencing a whole directory of sniffs. Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t* rule is referencing a directory of sniffs *".PHP_EOL; Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\tAdding sniff files from directory".PHP_EOL; Chris@0: } Chris@0: Chris@0: return $this->_expandSniffDirectory($ref, ($depth + 1)); Chris@0: } Chris@0: } else { Chris@0: if (is_file($ref) === false) { Chris@0: $error = "Referenced sniff \"$ref\" does not exist"; Chris@0: throw new PHP_CodeSniffer_Exception($error); Chris@0: } Chris@0: Chris@0: if (substr($ref, -9) === 'Sniff.php') { Chris@0: // A single sniff. Chris@0: return array($ref); Chris@0: } else { Chris@0: // Assume an external ruleset.xml file. Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t* rule is referencing a standard using ruleset path; processing *".PHP_EOL; Chris@0: } Chris@0: Chris@0: return $this->processRuleset($ref, ($depth + 2)); Chris@0: } Chris@0: }//end if Chris@0: Chris@0: }//end _expandRulesetReference() Chris@0: Chris@0: Chris@0: /** Chris@0: * Processes a rule from a ruleset XML file, overriding built-in defaults. Chris@0: * Chris@0: * @param SimpleXMLElement $rule The rule object from a ruleset XML file. Chris@0: * @param int $depth How many nested processing steps we are in. Chris@0: * This is only used for debug output. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: private function _processRule($rule, $depth=0) Chris@0: { Chris@0: $code = (string) $rule['ref']; Chris@0: Chris@0: // Custom severity. Chris@0: if (isset($rule->severity) === true Chris@0: && $this->_shouldProcessElement($rule->severity) === true Chris@0: ) { Chris@0: if (isset($this->ruleset[$code]) === false) { Chris@0: $this->ruleset[$code] = array(); Chris@0: } Chris@0: Chris@0: $this->ruleset[$code]['severity'] = (int) $rule->severity; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> severity set to ".(int) $rule->severity.PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: // Custom message type. Chris@0: if (isset($rule->type) === true Chris@0: && $this->_shouldProcessElement($rule->type) === true Chris@0: ) { Chris@0: if (isset($this->ruleset[$code]) === false) { Chris@0: $this->ruleset[$code] = array(); Chris@0: } Chris@0: Chris@0: $this->ruleset[$code]['type'] = (string) $rule->type; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> message type set to ".(string) $rule->type.PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: // Custom message. Chris@0: if (isset($rule->message) === true Chris@0: && $this->_shouldProcessElement($rule->message) === true Chris@0: ) { Chris@0: if (isset($this->ruleset[$code]) === false) { Chris@0: $this->ruleset[$code] = array(); Chris@0: } Chris@0: Chris@0: $this->ruleset[$code]['message'] = (string) $rule->message; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> message set to ".(string) $rule->message.PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: // Custom properties. Chris@0: if (isset($rule->properties) === true Chris@0: && $this->_shouldProcessElement($rule->properties) === true Chris@0: ) { Chris@0: foreach ($rule->properties->property as $prop) { Chris@0: if ($this->_shouldProcessElement($prop) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (isset($this->ruleset[$code]) === false) { Chris@0: $this->ruleset[$code] = array( Chris@0: 'properties' => array(), Chris@0: ); Chris@0: } else if (isset($this->ruleset[$code]['properties']) === false) { Chris@0: $this->ruleset[$code]['properties'] = array(); Chris@0: } Chris@0: Chris@0: $name = (string) $prop['name']; Chris@0: if (isset($prop['type']) === true Chris@0: && (string) $prop['type'] === 'array' Chris@0: ) { Chris@0: $value = (string) $prop['value']; Chris@0: $values = array(); Chris@0: foreach (explode(',', $value) as $val) { Chris@0: $v = ''; Chris@0: Chris@0: list($k,$v) = explode('=>', $val.'=>'); Chris@0: if ($v !== '') { Chris@0: $values[$k] = $v; Chris@0: } else { Chris@0: $values[] = $k; Chris@0: } Chris@0: } Chris@0: Chris@0: $this->ruleset[$code]['properties'][$name] = $values; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> array property \"$name\" set to \"$value\"".PHP_EOL; Chris@0: } Chris@0: } else { Chris@0: $this->ruleset[$code]['properties'][$name] = (string) $prop['value']; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> property \"$name\" set to \"".(string) $prop['value'].'"'.PHP_EOL; Chris@0: } Chris@0: }//end if Chris@0: }//end foreach Chris@0: }//end if Chris@0: Chris@0: // Ignore patterns. Chris@0: foreach ($rule->{'exclude-pattern'} as $pattern) { Chris@0: if ($this->_shouldProcessElement($pattern) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (isset($this->ignorePatterns[$code]) === false) { Chris@0: $this->ignorePatterns[$code] = array(); Chris@0: } Chris@0: Chris@0: if (isset($pattern['type']) === false) { Chris@0: $pattern['type'] = 'absolute'; Chris@0: } Chris@0: Chris@0: $this->ignorePatterns[$code][(string) $pattern] = (string) $pattern['type']; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo str_repeat("\t", $depth); Chris@0: echo "\t\t=> added sniff-specific ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: }//end _processRule() Chris@0: Chris@0: Chris@0: /** Chris@0: * Determine if an element should be processed or ignored. Chris@0: * Chris@0: * @param SimpleXMLElement $element An object from a ruleset XML file. Chris@0: * @param int $depth How many nested processing steps we are in. Chris@0: * This is only used for debug output. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function _shouldProcessElement($element, $depth=0) Chris@0: { Chris@0: if (isset($element['phpcbf-only']) === false Chris@0: && isset($element['phpcs-only']) === false Chris@0: ) { Chris@0: // No exceptions are being made. Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_CBF === true Chris@0: && isset($element['phpcbf-only']) === true Chris@0: && (string) $element['phpcbf-only'] === 'true' Chris@0: ) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_CBF === false Chris@0: && isset($element['phpcs-only']) === true Chris@0: && (string) $element['phpcs-only'] === 'true' Chris@0: ) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: return false; Chris@0: Chris@0: }//end _shouldProcessElement() Chris@0: Chris@0: Chris@0: /** Chris@0: * Loads and stores sniffs objects used for sniffing files. Chris@0: * Chris@0: * @param array $files Paths to the sniff files to register. Chris@0: * @param array $restrictions The sniff class names to restrict the allowed Chris@0: * listeners to. Chris@0: * @param array $exclusions The sniff class names to exclude from the Chris@0: * listeners list. Chris@0: * Chris@0: * @return void Chris@0: * @throws PHP_CodeSniffer_Exception If a sniff file path is invalid. Chris@0: */ Chris@0: public function registerSniffs($files, $restrictions, $exclusions) Chris@0: { Chris@0: $listeners = array(); Chris@0: Chris@0: foreach ($files as $file) { Chris@0: // Work out where the position of /StandardName/Sniffs/... is Chris@0: // so we can determine what the class will be called. Chris@0: $sniffPos = strrpos($file, DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR); Chris@0: if ($sniffPos === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $slashPos = strrpos(substr($file, 0, $sniffPos), DIRECTORY_SEPARATOR); Chris@0: if ($slashPos === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $className = substr($file, ($slashPos + 1)); Chris@0: Chris@0: if (substr_count($className, DIRECTORY_SEPARATOR) !== 3) { Chris@0: throw new PHP_CodeSniffer_Exception("Sniff file $className is not valid; sniff files must be located in a .../StandardName/Sniffs/CategoryName/ directory"); Chris@0: } Chris@0: Chris@0: $className = substr($className, 0, -4); Chris@0: $className = str_replace(DIRECTORY_SEPARATOR, '_', $className); Chris@0: Chris@0: // If they have specified a list of sniffs to restrict to, check Chris@0: // to see if this sniff is allowed. Chris@0: if (empty($restrictions) === false Chris@0: && in_array(strtolower($className), $restrictions) === false Chris@0: ) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // If they have specified a list of sniffs to exclude, check Chris@0: // to see if this sniff is allowed. Chris@0: if (empty($exclusions) === false Chris@0: && in_array(strtolower($className), $exclusions) === true Chris@0: ) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: include_once $file; Chris@0: Chris@0: // Support the use of PHP namespaces. If the class name we included Chris@0: // contains namespace separators instead of underscores, use this as the Chris@0: // class name from now on. Chris@0: $classNameNS = str_replace('_', '\\', $className); Chris@0: if (class_exists($classNameNS, false) === true) { Chris@0: $className = $classNameNS; Chris@0: } Chris@0: Chris@0: // Skip abstract classes. Chris@0: $reflection = new ReflectionClass($className); Chris@0: if ($reflection->isAbstract() === true) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $listeners[$className] = $className; Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 2) { Chris@0: echo "Registered $className".PHP_EOL; Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: $this->sniffs = $listeners; Chris@0: Chris@0: }//end registerSniffs() Chris@0: Chris@0: Chris@0: /** Chris@0: * Populates the array of PHP_CodeSniffer_Sniff's for this file. Chris@0: * Chris@0: * @return void Chris@0: * @throws PHP_CodeSniffer_Exception If sniff registration fails. Chris@0: */ Chris@0: public function populateTokenListeners() Chris@0: { Chris@0: // Construct a list of listeners indexed by token being listened for. Chris@0: $this->_tokenListeners = array(); Chris@0: Chris@0: foreach ($this->sniffs as $listenerClass) { Chris@0: // Work out the internal code for this sniff. Detect usage of namespace Chris@0: // separators instead of underscores to support PHP namespaces. Chris@0: if (strstr($listenerClass, '\\') === false) { Chris@0: $parts = explode('_', $listenerClass); Chris@0: } else { Chris@0: $parts = explode('\\', $listenerClass); Chris@0: } Chris@0: Chris@0: $code = $parts[0].'.'.$parts[2].'.'.$parts[3]; Chris@0: $code = substr($code, 0, -5); Chris@0: Chris@0: $this->listeners[$listenerClass] = new $listenerClass(); Chris@0: $this->sniffCodes[$code] = $listenerClass; Chris@0: Chris@0: // Set custom properties. Chris@0: if (isset($this->ruleset[$code]['properties']) === true) { Chris@0: foreach ($this->ruleset[$code]['properties'] as $name => $value) { Chris@0: $this->setSniffProperty($listenerClass, $name, $value); Chris@0: } Chris@0: } Chris@0: Chris@0: $tokenizers = array(); Chris@0: $vars = get_class_vars($listenerClass); Chris@0: if (isset($vars['supportedTokenizers']) === true) { Chris@0: foreach ($vars['supportedTokenizers'] as $tokenizer) { Chris@0: $tokenizers[$tokenizer] = $tokenizer; Chris@0: } Chris@0: } else { Chris@0: $tokenizers = array('PHP' => 'PHP'); Chris@0: } Chris@0: Chris@0: $tokens = $this->listeners[$listenerClass]->register(); Chris@0: if (is_array($tokens) === false) { Chris@0: $msg = "Sniff $listenerClass register() method must return an array"; Chris@0: throw new PHP_CodeSniffer_Exception($msg); Chris@0: } Chris@0: Chris@0: $parts = explode('_', str_replace('\\', '_', $listenerClass)); Chris@0: $listenerSource = $parts[0].'.'.$parts[2].'.'.substr($parts[3], 0, -5); Chris@0: $ignorePatterns = array(); Chris@0: $patterns = $this->getIgnorePatterns($listenerSource); Chris@0: foreach ($patterns as $pattern => $type) { Chris@0: // While there is support for a type of each pattern Chris@0: // (absolute or relative) we don't actually support it here. Chris@0: $replacements = array( Chris@0: '\\,' => ',', Chris@0: '*' => '.*', Chris@0: ); Chris@0: Chris@0: $ignorePatterns[] = strtr($pattern, $replacements); Chris@0: } Chris@0: Chris@0: foreach ($tokens as $token) { Chris@0: if (isset($this->_tokenListeners[$token]) === false) { Chris@0: $this->_tokenListeners[$token] = array(); Chris@0: } Chris@0: Chris@0: if (isset($this->_tokenListeners[$token][$listenerClass]) === false) { Chris@0: $this->_tokenListeners[$token][$listenerClass] = array( Chris@0: 'class' => $listenerClass, Chris@0: 'source' => $listenerSource, Chris@0: 'tokenizers' => $tokenizers, Chris@0: 'ignore' => $ignorePatterns, Chris@0: ); Chris@0: } Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: }//end populateTokenListeners() Chris@0: Chris@0: Chris@0: /** Chris@0: * Set a single property for a sniff. Chris@0: * Chris@0: * @param string $listenerClass The class name of the sniff. Chris@0: * @param string $name The name of the property to change. Chris@0: * @param string $value The new value of the property. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function setSniffProperty($listenerClass, $name, $value) Chris@0: { Chris@0: // Setting a property for a sniff we are not using. Chris@0: if (isset($this->listeners[$listenerClass]) === false) { Chris@0: return; Chris@0: } Chris@0: Chris@0: $name = trim($name); Chris@0: if (is_string($value) === true) { Chris@0: $value = trim($value); Chris@0: } Chris@0: Chris@0: // Special case for booleans. Chris@0: if ($value === 'true') { Chris@0: $value = true; Chris@0: } else if ($value === 'false') { Chris@0: $value = false; Chris@0: } Chris@0: Chris@0: $this->listeners[$listenerClass]->$name = $value; Chris@0: Chris@0: }//end setSniffProperty() Chris@0: Chris@0: Chris@0: /** Chris@0: * Get a list of files that will be processed. Chris@0: * Chris@0: * If passed directories, this method will find all files within them. Chris@0: * The method will also perform file extension and ignore pattern filtering. Chris@0: * Chris@0: * @param string $paths A list of file or directory paths to process. Chris@0: * @param boolean $local If true, only process 1 level of files in directories Chris@0: * Chris@0: * @return array Chris@0: * @throws Exception If there was an error opening a directory. Chris@0: * @see shouldProcessFile() Chris@0: */ Chris@0: public function getFilesToProcess($paths, $local=false) Chris@0: { Chris@0: $files = array(); Chris@0: Chris@0: foreach ($paths as $path) { Chris@0: if (is_dir($path) === true || self::isPharFile($path) === true) { Chris@0: if (self::isPharFile($path) === true) { Chris@0: $path = 'phar://'.$path; Chris@0: } Chris@0: Chris@0: if ($local === true) { Chris@0: $di = new DirectoryIterator($path); Chris@0: } else { Chris@0: $di = new RecursiveIteratorIterator( Chris@0: new RecursiveDirectoryIterator($path), Chris@0: 0, Chris@0: RecursiveIteratorIterator::CATCH_GET_CHILD Chris@0: ); Chris@0: } Chris@0: Chris@0: foreach ($di as $file) { Chris@0: // Check if the file exists after all symlinks are resolved. Chris@0: $filePath = self::realpath($file->getPathname()); Chris@0: if ($filePath === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (is_dir($filePath) === true) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($this->shouldProcessFile($file->getPathname(), $path) === false) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $files[] = $file->getPathname(); Chris@0: }//end foreach Chris@0: } else { Chris@0: if ($this->shouldIgnoreFile($path, dirname($path)) === true) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $files[] = $path; Chris@0: }//end if Chris@0: }//end foreach Chris@0: Chris@0: return $files; Chris@0: Chris@0: }//end getFilesToProcess() Chris@0: Chris@0: Chris@0: /** Chris@0: * Checks filtering rules to see if a file should be checked. Chris@0: * Chris@0: * Checks both file extension filters and path ignore filters. Chris@0: * Chris@0: * @param string $path The path to the file being checked. Chris@0: * @param string $basedir The directory to use for relative path checks. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function shouldProcessFile($path, $basedir) Chris@0: { Chris@0: // Check that the file's extension is one we are checking. Chris@0: // We are strict about checking the extension and we don't Chris@0: // let files through with no extension or that start with a dot. Chris@0: $fileName = basename($path); Chris@0: $fileParts = explode('.', $fileName); Chris@0: if ($fileParts[0] === $fileName || $fileParts[0] === '') { Chris@0: return false; Chris@0: } Chris@0: Chris@0: // Checking multi-part file extensions, so need to create a Chris@0: // complete extension list and make sure one is allowed. Chris@0: $extensions = array(); Chris@0: array_shift($fileParts); Chris@0: foreach ($fileParts as $part) { Chris@0: $extensions[implode('.', $fileParts)] = 1; Chris@0: array_shift($fileParts); Chris@0: } Chris@0: Chris@0: $matches = array_intersect_key($extensions, $this->allowedFileExtensions); Chris@0: if (empty($matches) === true) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: // If the file's path matches one of our ignore patterns, skip it. Chris@0: if ($this->shouldIgnoreFile($path, $basedir) === true) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: return true; Chris@0: Chris@0: }//end shouldProcessFile() Chris@0: Chris@0: Chris@0: /** Chris@0: * Checks filtering rules to see if a file should be ignored. Chris@0: * Chris@0: * @param string $path The path to the file being checked. Chris@0: * @param string $basedir The directory to use for relative path checks. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function shouldIgnoreFile($path, $basedir) Chris@0: { Chris@0: $relativePath = $path; Chris@0: if (strpos($path, $basedir) === 0) { Chris@0: // The +1 cuts off the directory separator as well. Chris@0: $relativePath = substr($path, (strlen($basedir) + 1)); Chris@0: } Chris@0: Chris@0: foreach ($this->ignorePatterns as $pattern => $type) { Chris@0: if (is_array($type) === true) { Chris@0: // A sniff specific ignore pattern. Chris@0: continue; Chris@0: } Chris@0: Chris@0: // Maintains backwards compatibility in case the ignore pattern does Chris@0: // not have a relative/absolute value. Chris@0: if (is_int($pattern) === true) { Chris@0: $pattern = $type; Chris@0: $type = 'absolute'; Chris@0: } Chris@0: Chris@0: $replacements = array( Chris@0: '\\,' => ',', Chris@0: '*' => '.*', Chris@0: ); Chris@0: Chris@0: // We assume a / directory separator, as do the exclude rules Chris@0: // most developers write, so we need a special case for any system Chris@0: // that is different. Chris@0: if (DIRECTORY_SEPARATOR === '\\') { Chris@0: $replacements['/'] = '\\\\'; Chris@0: } Chris@0: Chris@0: $pattern = strtr($pattern, $replacements); Chris@0: Chris@0: if ($type === 'relative') { Chris@0: $testPath = $relativePath; Chris@0: } else { Chris@0: $testPath = $path; Chris@0: } Chris@0: Chris@0: $pattern = '`'.$pattern.'`i'; Chris@0: if (preg_match($pattern, $testPath) === 1) { Chris@0: return true; Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: return false; Chris@0: Chris@0: }//end shouldIgnoreFile() Chris@0: Chris@0: Chris@0: /** Chris@0: * Run the code sniffs over a single given file. Chris@0: * Chris@0: * Processes the file and runs the PHP_CodeSniffer sniffs to verify that it Chris@0: * conforms with the standard. Returns the processed file object, or NULL Chris@0: * if no file was processed due to error. Chris@0: * Chris@0: * @param string $file The file to process. Chris@0: * @param string $contents The contents to parse. If NULL, the content Chris@0: * is taken from the file system. Chris@0: * Chris@0: * @return PHP_CodeSniffer_File Chris@0: * @throws PHP_CodeSniffer_Exception If the file could not be processed. Chris@0: * @see _processFile() Chris@0: */ Chris@0: public function processFile($file, $contents=null) Chris@0: { Chris@0: if ($contents === null && file_exists($file) === false) { Chris@0: throw new PHP_CodeSniffer_Exception("Source file $file does not exist"); Chris@0: } Chris@0: Chris@0: $filePath = self::realpath($file); Chris@0: if ($filePath === false) { Chris@0: $filePath = $file; Chris@0: } Chris@0: Chris@0: // Before we go and spend time tokenizing this file, just check Chris@0: // to see if there is a tag up top to indicate that the whole Chris@0: // file should be ignored. It must be on one of the first two lines. Chris@0: $firstContent = $contents; Chris@0: if ($contents === null && is_readable($filePath) === true) { Chris@0: $handle = fopen($filePath, 'r'); Chris@0: stream_set_blocking($handle, true); Chris@0: if ($handle !== false) { Chris@0: $firstContent = fgets($handle); Chris@0: $firstContent .= fgets($handle); Chris@0: fclose($handle); Chris@0: Chris@0: if (strpos($firstContent, '@codingStandardsIgnoreFile') !== false) { Chris@0: // We are ignoring the whole file. Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0) { Chris@0: echo 'Ignoring '.basename($filePath).PHP_EOL; Chris@0: } Chris@0: Chris@0: return null; Chris@0: } Chris@0: } Chris@0: }//end if Chris@0: Chris@0: try { Chris@0: $phpcsFile = $this->_processFile($file, $contents); Chris@0: } catch (Exception $e) { Chris@0: $trace = $e->getTrace(); Chris@0: Chris@0: $filename = $trace[0]['args'][0]; Chris@0: if (is_object($filename) === true Chris@0: && get_class($filename) === 'PHP_CodeSniffer_File' Chris@0: ) { Chris@0: $filename = $filename->getFilename(); Chris@0: } else if (is_numeric($filename) === true) { Chris@0: // See if we can find the PHP_CodeSniffer_File object. Chris@0: foreach ($trace as $data) { Chris@0: if (isset($data['args'][0]) === true Chris@0: && ($data['args'][0] instanceof PHP_CodeSniffer_File) === true Chris@0: ) { Chris@0: $filename = $data['args'][0]->getFilename(); Chris@0: } Chris@0: } Chris@0: } else if (is_string($filename) === false) { Chris@0: $filename = (string) $filename; Chris@0: } Chris@0: Chris@0: $errorMessage = '"'.$e->getMessage().'" at '.$e->getFile().':'.$e->getLine(); Chris@0: $error = "An error occurred during processing; checking has been aborted. The error message was: $errorMessage"; Chris@0: Chris@0: $phpcsFile = new PHP_CodeSniffer_File( Chris@0: $filename, Chris@0: $this->_tokenListeners, Chris@0: $this->ruleset, Chris@0: $this Chris@0: ); Chris@0: Chris@0: $phpcsFile->addError($error, null); Chris@0: }//end try Chris@0: Chris@0: $cliValues = $this->cli->getCommandLineValues(); Chris@0: Chris@0: if (PHP_CODESNIFFER_INTERACTIVE === false) { Chris@0: // Cache the report data for this file so we can unset it to save memory. Chris@0: $this->reporting->cacheFileReport($phpcsFile, $cliValues); Chris@0: $phpcsFile->cleanUp(); Chris@0: return $phpcsFile; Chris@0: } Chris@0: Chris@0: /* Chris@0: Running interactively. Chris@0: Print the error report for the current file and then wait for user input. Chris@0: */ Chris@0: Chris@0: // Get current violations and then clear the list to make sure Chris@0: // we only print violations for a single file each time. Chris@0: $numErrors = null; Chris@0: while ($numErrors !== 0) { Chris@0: $numErrors = ($phpcsFile->getErrorCount() + $phpcsFile->getWarningCount()); Chris@0: if ($numErrors === 0) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $reportClass = $this->reporting->factory('full'); Chris@0: $reportData = $this->reporting->prepareFileReport($phpcsFile); Chris@0: $reportClass->generateFileReport($reportData, $phpcsFile, $cliValues['showSources'], $cliValues['reportWidth']); Chris@0: Chris@0: echo ' to recheck, [s] to skip or [q] to quit : '; Chris@0: $input = fgets(STDIN); Chris@0: $input = trim($input); Chris@0: Chris@0: switch ($input) { Chris@0: case 's': Chris@0: break(2); Chris@0: case 'q': Chris@0: exit(0); Chris@0: break; Chris@0: default: Chris@0: // Repopulate the sniffs because some of them save their state Chris@0: // and only clear it when the file changes, but we are rechecking Chris@0: // the same file. Chris@0: $this->populateTokenListeners(); Chris@0: $phpcsFile = $this->_processFile($file, $contents); Chris@0: break; Chris@0: } Chris@0: }//end while Chris@0: Chris@0: return $phpcsFile; Chris@0: Chris@0: }//end processFile() Chris@0: Chris@0: Chris@0: /** Chris@0: * Process the sniffs for a single file. Chris@0: * Chris@0: * Does raw processing only. No interactive support or error checking. Chris@0: * Chris@0: * @param string $file The file to process. Chris@0: * @param string $contents The contents to parse. If NULL, the content Chris@0: * is taken from the file system. Chris@0: * Chris@0: * @return PHP_CodeSniffer_File Chris@0: * @see processFile() Chris@0: */ Chris@0: private function _processFile($file, $contents) Chris@0: { Chris@0: $stdin = false; Chris@0: $cliValues = $this->cli->getCommandLineValues(); Chris@0: if (empty($cliValues['files']) === true) { Chris@0: $stdin = true; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0 || (PHP_CODESNIFFER_CBF === true && $stdin === false)) { Chris@0: $startTime = microtime(true); Chris@0: echo 'Processing '.basename($file).' '; Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 1) { Chris@0: echo PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: $phpcsFile = new PHP_CodeSniffer_File( Chris@0: $file, Chris@0: $this->_tokenListeners, Chris@0: $this->ruleset, Chris@0: $this Chris@0: ); Chris@0: Chris@0: $phpcsFile->start($contents); Chris@0: Chris@0: if (PHP_CODESNIFFER_VERBOSITY > 0 || (PHP_CODESNIFFER_CBF === true && $stdin === false)) { Chris@0: $timeTaken = ((microtime(true) - $startTime) * 1000); Chris@0: if ($timeTaken < 1000) { Chris@0: $timeTaken = round($timeTaken); Chris@0: echo "DONE in {$timeTaken}ms"; Chris@0: } else { Chris@0: $timeTaken = round(($timeTaken / 1000), 2); Chris@0: echo "DONE in $timeTaken secs"; Chris@0: } Chris@0: Chris@0: if (PHP_CODESNIFFER_CBF === true) { Chris@0: $errors = $phpcsFile->getFixableCount(); Chris@0: echo " ($errors fixable violations)".PHP_EOL; Chris@0: } else { Chris@0: $errors = $phpcsFile->getErrorCount(); Chris@0: $warnings = $phpcsFile->getWarningCount(); Chris@0: echo " ($errors errors, $warnings warnings)".PHP_EOL; Chris@0: } Chris@0: } Chris@0: Chris@0: return $phpcsFile; Chris@0: Chris@0: }//end _processFile() Chris@0: Chris@0: Chris@0: /** Chris@0: * Generates documentation for a coding standard. Chris@0: * Chris@0: * @param string $standard The standard to generate docs for Chris@0: * @param array $sniffs A list of sniffs to limit the docs to. Chris@0: * @param string $generator The name of the generator class to use. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public function generateDocs($standard, array $sniffs=array(), $generator='Text') Chris@0: { Chris@0: if (class_exists('PHP_CodeSniffer_DocGenerators_'.$generator, true) === false) { Chris@0: throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_DocGenerators_'.$generator.' not found'); Chris@0: } Chris@0: Chris@0: $class = "PHP_CodeSniffer_DocGenerators_$generator"; Chris@0: $generator = new $class($standard, $sniffs); Chris@0: Chris@0: $generator->generate(); Chris@0: Chris@0: }//end generateDocs() Chris@0: Chris@0: Chris@0: /** Chris@0: * Gets the array of PHP_CodeSniffer_Sniff's. Chris@0: * Chris@0: * @return PHP_CodeSniffer_Sniff[] Chris@0: */ Chris@0: public function getSniffs() Chris@0: { Chris@0: return $this->listeners; Chris@0: Chris@0: }//end getSniffs() Chris@0: Chris@0: Chris@0: /** Chris@0: * Gets the array of PHP_CodeSniffer_Sniff's indexed by token type. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public function getTokenSniffs() Chris@0: { Chris@0: return $this->_tokenListeners; Chris@0: Chris@0: }//end getTokenSniffs() Chris@0: Chris@0: Chris@0: /** Chris@0: * Returns true if the specified string is in the camel caps format. Chris@0: * Chris@0: * @param string $string The string the verify. Chris@0: * @param boolean $classFormat If true, check to see if the string is in the Chris@0: * class format. Class format strings must start Chris@0: * with a capital letter and contain no Chris@0: * underscores. Chris@0: * @param boolean $public If true, the first character in the string Chris@0: * must be an a-z character. If false, the Chris@0: * character must be an underscore. This Chris@0: * argument is only applicable if $classFormat Chris@0: * is false. Chris@0: * @param boolean $strict If true, the string must not have two capital Chris@0: * letters next to each other. If false, a Chris@0: * relaxed camel caps policy is used to allow Chris@0: * for acronyms. Chris@0: * Chris@0: * @return boolean Chris@0: */ Chris@0: public static function isCamelCaps( Chris@0: $string, Chris@0: $classFormat=false, Chris@0: $public=true, Chris@0: $strict=true Chris@0: ) { Chris@0: // Check the first character first. Chris@0: if ($classFormat === false) { Chris@0: $legalFirstChar = ''; Chris@0: if ($public === false) { Chris@0: $legalFirstChar = '[_]'; Chris@0: } Chris@0: Chris@0: if ($strict === false) { Chris@0: // Can either start with a lowercase letter, or multiple uppercase Chris@0: // in a row, representing an acronym. Chris@0: $legalFirstChar .= '([A-Z]{2,}|[a-z])'; Chris@0: } else { Chris@0: $legalFirstChar .= '[a-z]'; Chris@0: } Chris@0: } else { Chris@0: $legalFirstChar = '[A-Z]'; Chris@0: } Chris@0: Chris@0: if (preg_match("/^$legalFirstChar/", $string) === 0) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: // Check that the name only contains legal characters. Chris@0: $legalChars = 'a-zA-Z0-9'; Chris@0: if (preg_match("|[^$legalChars]|", substr($string, 1)) > 0) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: if ($strict === true) { Chris@0: // Check that there are not two capital letters next to each other. Chris@0: $length = strlen($string); Chris@0: $lastCharWasCaps = $classFormat; Chris@0: Chris@0: for ($i = 1; $i < $length; $i++) { Chris@0: $ascii = ord($string{$i}); Chris@0: if ($ascii >= 48 && $ascii <= 57) { Chris@0: // The character is a number, so it cant be a capital. Chris@0: $isCaps = false; Chris@0: } else { Chris@0: if (strtoupper($string{$i}) === $string{$i}) { Chris@0: $isCaps = true; Chris@0: } else { Chris@0: $isCaps = false; Chris@0: } Chris@0: } Chris@0: Chris@0: if ($isCaps === true && $lastCharWasCaps === true) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $lastCharWasCaps = $isCaps; Chris@0: } Chris@0: }//end if Chris@0: Chris@0: return true; Chris@0: Chris@0: }//end isCamelCaps() Chris@0: Chris@0: Chris@0: /** Chris@0: * Returns true if the specified string is in the underscore caps format. Chris@0: * Chris@0: * @param string $string The string to verify. Chris@0: * Chris@0: * @return boolean Chris@0: */ Chris@0: public static function isUnderscoreName($string) Chris@0: { Chris@0: // If there are space in the name, it can't be valid. Chris@0: if (strpos($string, ' ') !== false) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $validName = true; Chris@0: $nameBits = explode('_', $string); Chris@0: Chris@0: if (preg_match('|^[A-Z]|', $string) === 0) { Chris@0: // Name does not begin with a capital letter. Chris@0: $validName = false; Chris@0: } else { Chris@0: foreach ($nameBits as $bit) { Chris@0: if ($bit === '') { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($bit{0} !== strtoupper($bit{0})) { Chris@0: $validName = false; Chris@0: break; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $validName; Chris@0: Chris@0: }//end isUnderscoreName() Chris@0: Chris@0: Chris@0: /** Chris@0: * Returns a valid variable type for param/var tag. Chris@0: * Chris@0: * If type is not one of the standard type, it must be a custom type. Chris@0: * Returns the correct type name suggestion if type name is invalid. Chris@0: * Chris@0: * @param string $varType The variable type to process. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public static function suggestType($varType) Chris@0: { Chris@0: if ($varType === '') { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: if (in_array($varType, self::$allowedTypes) === true) { Chris@0: return $varType; Chris@0: } else { Chris@0: $lowerVarType = strtolower($varType); Chris@0: switch ($lowerVarType) { Chris@0: case 'bool': Chris@0: case 'boolean': Chris@0: return 'boolean'; Chris@0: case 'double': Chris@0: case 'real': Chris@0: case 'float': Chris@0: return 'float'; Chris@0: case 'int': Chris@0: case 'integer': Chris@0: return 'integer'; Chris@0: case 'array()': Chris@0: case 'array': Chris@0: return 'array'; Chris@0: }//end switch Chris@0: Chris@0: if (strpos($lowerVarType, 'array(') !== false) { Chris@0: // Valid array declaration: Chris@0: // array, array(type), array(type1 => type2). Chris@0: $matches = array(); Chris@0: $pattern = '/^array\(\s*([^\s^=^>]*)(\s*=>\s*(.*))?\s*\)/i'; Chris@0: if (preg_match($pattern, $varType, $matches) !== 0) { Chris@0: $type1 = ''; Chris@0: if (isset($matches[1]) === true) { Chris@0: $type1 = $matches[1]; Chris@0: } Chris@0: Chris@0: $type2 = ''; Chris@0: if (isset($matches[3]) === true) { Chris@0: $type2 = $matches[3]; Chris@0: } Chris@0: Chris@0: $type1 = self::suggestType($type1); Chris@0: $type2 = self::suggestType($type2); Chris@0: if ($type2 !== '') { Chris@0: $type2 = ' => '.$type2; Chris@0: } Chris@0: Chris@0: return "array($type1$type2)"; Chris@0: } else { Chris@0: return 'array'; Chris@0: }//end if Chris@0: } else if (in_array($lowerVarType, self::$allowedTypes) === true) { Chris@0: // A valid type, but not lower cased. Chris@0: return $lowerVarType; Chris@0: } else { Chris@0: // Must be a custom type name. Chris@0: return $varType; Chris@0: }//end if Chris@0: }//end if Chris@0: Chris@0: }//end suggestType() Chris@0: Chris@0: Chris@0: /** Chris@0: * Prepares token content for output to screen. Chris@0: * Chris@0: * Replaces invisible characters so they are visible. On non-Windows Chris@0: * OSes it will also colour the invisible characters. Chris@0: * Chris@0: * @param string $content The content to prepare. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public static function prepareForOutput($content) Chris@0: { Chris@0: if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { Chris@0: $content = str_replace("\r", '\r', $content); Chris@0: $content = str_replace("\n", '\n', $content); Chris@0: $content = str_replace("\t", '\t', $content); Chris@0: } else { Chris@0: $content = str_replace("\r", "\033[30;1m\\r\033[0m", $content); Chris@0: $content = str_replace("\n", "\033[30;1m\\n\033[0m", $content); Chris@0: $content = str_replace("\t", "\033[30;1m\\t\033[0m", $content); Chris@0: $content = str_replace(' ', "\033[30;1m·\033[0m", $content); Chris@0: } Chris@0: Chris@0: return $content; Chris@0: Chris@0: }//end prepareForOutput() Chris@0: Chris@0: Chris@0: /** Chris@0: * Get a list paths where standards are installed. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public static function getInstalledStandardPaths() Chris@0: { Chris@0: $installedPaths = array(dirname(__FILE__).DIRECTORY_SEPARATOR.'CodeSniffer'.DIRECTORY_SEPARATOR.'Standards'); Chris@0: $configPaths = PHP_CodeSniffer::getConfigData('installed_paths'); Chris@0: if ($configPaths !== null) { Chris@0: $installedPaths = array_merge($installedPaths, explode(',', $configPaths)); Chris@0: } Chris@0: Chris@0: $resolvedInstalledPaths = array(); Chris@0: foreach ($installedPaths as $installedPath) { Chris@0: if (substr($installedPath, 0, 1) === '.') { Chris@0: $installedPath = dirname(__FILE__).DIRECTORY_SEPARATOR.$installedPath; Chris@0: } Chris@0: Chris@0: $resolvedInstalledPaths[] = $installedPath; Chris@0: } Chris@0: Chris@0: return $resolvedInstalledPaths; Chris@0: Chris@0: }//end getInstalledStandardPaths() Chris@0: Chris@0: Chris@0: /** Chris@0: * Get a list of all coding standards installed. Chris@0: * Chris@0: * Coding standards are directories located in the Chris@0: * CodeSniffer/Standards directory. Valid coding standards Chris@0: * include a Sniffs subdirectory. Chris@0: * Chris@0: * @param boolean $includeGeneric If true, the special "Generic" Chris@0: * coding standard will be included Chris@0: * if installed. Chris@0: * @param string $standardsDir A specific directory to look for standards Chris@0: * in. If not specified, PHP_CodeSniffer will Chris@0: * look in its default locations. Chris@0: * Chris@0: * @return array Chris@0: * @see isInstalledStandard() Chris@0: */ Chris@0: public static function getInstalledStandards( Chris@0: $includeGeneric=false, Chris@0: $standardsDir='' Chris@0: ) { Chris@0: $installedStandards = array(); Chris@0: Chris@0: if ($standardsDir === '') { Chris@0: $installedPaths = self::getInstalledStandardPaths(); Chris@0: } else { Chris@0: $installedPaths = array($standardsDir); Chris@0: } Chris@0: Chris@0: foreach ($installedPaths as $standardsDir) { Chris@0: $di = new DirectoryIterator($standardsDir); Chris@0: foreach ($di as $file) { Chris@0: if ($file->isDir() === true && $file->isDot() === false) { Chris@0: $filename = $file->getFilename(); Chris@0: Chris@0: // Ignore the special "Generic" standard. Chris@0: if ($includeGeneric === false && $filename === 'Generic') { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // Valid coding standard dirs include a ruleset. Chris@0: $csFile = $file->getPathname().'/ruleset.xml'; Chris@0: if (is_file($csFile) === true) { Chris@0: $installedStandards[] = $filename; Chris@0: } Chris@0: } Chris@0: } Chris@0: }//end foreach Chris@0: Chris@0: return $installedStandards; Chris@0: Chris@0: }//end getInstalledStandards() Chris@0: Chris@0: Chris@0: /** Chris@0: * Determine if a standard is installed. Chris@0: * Chris@0: * Coding standards are directories located in the Chris@0: * CodeSniffer/Standards directory. Valid coding standards Chris@0: * include a ruleset.xml file. Chris@0: * Chris@0: * @param string $standard The name of the coding standard. Chris@0: * Chris@0: * @return boolean Chris@0: * @see getInstalledStandards() Chris@0: */ Chris@0: public static function isInstalledStandard($standard) Chris@0: { Chris@0: $path = self::getInstalledStandardPath($standard); Chris@0: if ($path !== null && strpos($path, 'ruleset.xml') !== false) { Chris@0: return true; Chris@0: } else { Chris@0: // This could be a custom standard, installed outside our Chris@0: // standards directory. Chris@0: $standard = self::realPath($standard); Chris@0: Chris@0: // Might be an actual ruleset file itself. Chris@0: // If it has an XML extension, let's at least try it. Chris@0: if (is_file($standard) === true Chris@0: && (substr(strtolower($standard), -4) === '.xml' Chris@0: || substr(strtolower($standard), -9) === '.xml.dist') Chris@0: ) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: // If it is a directory with a ruleset.xml file in it, Chris@0: // it is a standard. Chris@0: $ruleset = rtrim($standard, ' /\\').DIRECTORY_SEPARATOR.'ruleset.xml'; Chris@0: if (is_file($ruleset) === true) { Chris@0: return true; Chris@0: } Chris@0: }//end if Chris@0: Chris@0: return false; Chris@0: Chris@0: }//end isInstalledStandard() Chris@0: Chris@0: Chris@0: /** Chris@0: * Return the path of an installed coding standard. Chris@0: * Chris@0: * Coding standards are directories located in the Chris@0: * CodeSniffer/Standards directory. Valid coding standards Chris@0: * include a ruleset.xml file. Chris@0: * Chris@0: * @param string $standard The name of the coding standard. Chris@0: * Chris@0: * @return string|null Chris@0: */ Chris@0: public static function getInstalledStandardPath($standard) Chris@0: { Chris@0: $installedPaths = self::getInstalledStandardPaths(); Chris@0: foreach ($installedPaths as $installedPath) { Chris@0: $standardPath = $installedPath.DIRECTORY_SEPARATOR.$standard; Chris@0: $path = self::realpath($standardPath.DIRECTORY_SEPARATOR.'ruleset.xml'); Chris@0: if (is_file($path) === true) { Chris@0: return $path; Chris@0: } else if (self::isPharFile($standardPath) === true) { Chris@0: $path = self::realpath($standardPath); Chris@0: if ($path !== false) { Chris@0: return $path; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return null; Chris@0: Chris@0: }//end getInstalledStandardPath() Chris@0: Chris@0: Chris@0: /** Chris@0: * Get a single config value. Chris@0: * Chris@0: * Config data is stored in the data dir, in a file called Chris@0: * CodeSniffer.conf. It is a simple PHP array. Chris@0: * Chris@0: * @param string $key The name of the config value. Chris@0: * Chris@0: * @return string|null Chris@0: * @see setConfigData() Chris@0: * @see getAllConfigData() Chris@0: */ Chris@0: public static function getConfigData($key) Chris@0: { Chris@0: $phpCodeSnifferConfig = self::getAllConfigData(); Chris@0: Chris@0: if ($phpCodeSnifferConfig === null) { Chris@0: return null; Chris@0: } Chris@0: Chris@0: if (isset($phpCodeSnifferConfig[$key]) === false) { Chris@0: return null; Chris@0: } Chris@0: Chris@0: return $phpCodeSnifferConfig[$key]; Chris@0: Chris@0: }//end getConfigData() Chris@0: Chris@0: Chris@0: /** Chris@0: * Set a single config value. Chris@0: * Chris@0: * Config data is stored in the data dir, in a file called Chris@0: * CodeSniffer.conf. It is a simple PHP array. Chris@0: * Chris@0: * @param string $key The name of the config value. Chris@0: * @param string|null $value The value to set. If null, the config Chris@0: * entry is deleted, reverting it to the Chris@0: * default value. Chris@0: * @param boolean $temp Set this config data temporarily for this Chris@0: * script run. This will not write the config Chris@0: * data to the config file. Chris@0: * Chris@0: * @return boolean Chris@0: * @see getConfigData() Chris@0: * @throws PHP_CodeSniffer_Exception If the config file can not be written. Chris@0: */ Chris@0: public static function setConfigData($key, $value, $temp=false) Chris@0: { Chris@0: if ($temp === false) { Chris@0: $path = ''; Chris@0: if (is_callable('Phar::running') === true) { Chris@0: $path = Phar::running(false); Chris@0: } Chris@0: Chris@0: if ($path !== '') { Chris@0: $configFile = dirname($path).'/CodeSniffer.conf'; Chris@0: } else { Chris@0: $configFile = dirname(__FILE__).'/CodeSniffer.conf'; Chris@0: if (is_file($configFile) === false Chris@0: && strpos('@data_dir@', '@data_dir') === false Chris@0: ) { Chris@0: // If data_dir was replaced, this is a PEAR install and we can Chris@0: // use the PEAR data dir to store the conf file. Chris@0: $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf'; Chris@0: } Chris@0: } Chris@0: Chris@0: if (is_file($configFile) === true Chris@0: && is_writable($configFile) === false Chris@0: ) { Chris@0: $error = 'Config file '.$configFile.' is not writable'; Chris@0: throw new PHP_CodeSniffer_Exception($error); Chris@0: } Chris@0: }//end if Chris@0: Chris@0: $phpCodeSnifferConfig = self::getAllConfigData(); Chris@0: Chris@0: if ($value === null) { Chris@0: if (isset($phpCodeSnifferConfig[$key]) === true) { Chris@0: unset($phpCodeSnifferConfig[$key]); Chris@0: } Chris@0: } else { Chris@0: $phpCodeSnifferConfig[$key] = $value; Chris@0: } Chris@0: Chris@0: if ($temp === false) { Chris@0: $output = '<'.'?php'."\n".' $phpCodeSnifferConfig = '; Chris@0: $output .= var_export($phpCodeSnifferConfig, true); Chris@0: $output .= "\n?".'>'; Chris@0: Chris@0: if (file_put_contents($configFile, $output) === false) { Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'] = $phpCodeSnifferConfig; Chris@0: Chris@0: return true; Chris@0: Chris@0: }//end setConfigData() Chris@0: Chris@0: Chris@0: /** Chris@0: * Get all config data in an array. Chris@0: * Chris@0: * @return array Chris@0: * @see getConfigData() Chris@0: */ Chris@0: public static function getAllConfigData() Chris@0: { Chris@0: if (isset($GLOBALS['PHP_CODESNIFFER_CONFIG_DATA']) === true) { Chris@0: return $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA']; Chris@0: } Chris@0: Chris@0: $path = ''; Chris@0: if (is_callable('Phar::running') === true) { Chris@0: $path = Phar::running(false); Chris@0: } Chris@0: Chris@0: if ($path !== '') { Chris@0: $configFile = dirname($path).'/CodeSniffer.conf'; Chris@0: } else { Chris@0: $configFile = dirname(__FILE__).'/CodeSniffer.conf'; Chris@0: if (is_file($configFile) === false) { Chris@0: $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf'; Chris@0: } Chris@0: } Chris@0: Chris@0: if (is_file($configFile) === false) { Chris@0: $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'] = array(); Chris@0: return array(); Chris@0: } Chris@0: Chris@0: include $configFile; Chris@0: $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'] = $phpCodeSnifferConfig; Chris@0: return $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA']; Chris@0: Chris@0: }//end getAllConfigData() Chris@0: Chris@0: Chris@0: /** Chris@0: * Return TRUE, if the path is a phar file. Chris@0: * Chris@0: * @param string $path The path to use. Chris@0: * Chris@0: * @return mixed Chris@0: */ Chris@0: public static function isPharFile($path) Chris@0: { Chris@0: if (strpos($path, 'phar://') === 0) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: return false; Chris@0: Chris@0: }//end isPharFile() Chris@0: Chris@0: Chris@0: /** Chris@0: * CodeSniffer alternative for realpath. Chris@0: * Chris@0: * Allows for phar support. Chris@0: * Chris@0: * @param string $path The path to use. Chris@0: * Chris@0: * @return mixed Chris@0: */ Chris@0: public static function realpath($path) Chris@0: { Chris@0: // Support the path replacement of ~ with the user's home directory. Chris@0: if (substr($path, 0, 2) === '~/') { Chris@0: $homeDir = getenv('HOME'); Chris@0: if ($homeDir !== false) { Chris@0: $path = $homeDir.substr($path, 1); Chris@0: } Chris@0: } Chris@0: Chris@0: // No extra work needed if this is not a phar file. Chris@0: if (self::isPharFile($path) === false) { Chris@0: return realpath($path); Chris@0: } Chris@0: Chris@0: // Before trying to break down the file path, Chris@0: // check if it exists first because it will mostly not Chris@0: // change after running the below code. Chris@0: if (file_exists($path) === true) { Chris@0: return $path; Chris@0: } Chris@0: Chris@0: $phar = Phar::running(false); Chris@0: $extra = str_replace('phar://'.$phar, '', $path); Chris@0: $path = realpath($phar); Chris@0: if ($path === false) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $path = 'phar://'.$path.$extra; Chris@0: if (file_exists($path) === true) { Chris@0: return $path; Chris@0: } Chris@0: Chris@0: return false; Chris@0: Chris@0: }//end realpath() Chris@0: Chris@0: Chris@0: /** Chris@0: * CodeSniffer alternative for chdir(). Chris@0: * Chris@0: * Allows for phar support. Chris@0: * Chris@0: * @param string $path The path to use. Chris@0: * Chris@0: * @return void Chris@0: */ Chris@0: public static function chdir($path) Chris@0: { Chris@0: if (self::isPharFile($path) === true) { Chris@0: $phar = Phar::running(false); Chris@0: chdir(dirname($phar)); Chris@0: } else { Chris@0: chdir($path); Chris@0: } Chris@0: Chris@0: }//end chdir() Chris@0: Chris@0: Chris@0: }//end class