Config data is stored in the data dir, in a file called
CodeSniffer.conf. It is a simple PHP array.
public static setConfigData ( string $key, string | null $value, boolean $temp = false ) : boolean | ||
$key | string | The name of the config value. |
$value | string | null | The value to set. If null, the config entry is deleted, reverting it to the default value. |
$temp | boolean | Set this config data temporarily for this script run. This will not write the config data to the config file. |
리턴 | boolean |
/** * Sniff a file and return resulting file object * * @param string $filename Filename to sniff * @param string $targetPhpVersion Value of 'testVersion' to set on PHPCS object * @return PHP_CodeSniffer_File File object */ public function sniffFile($filename, $targetPhpVersion = null) { if (null !== $targetPhpVersion) { PHP_CodeSniffer::setConfigData('testVersion', $targetPhpVersion, true); } $filename = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . $filename; try { $phpcsFile = self::$phpcs->processFile($filename); } catch (Exception $e) { $this->fail('An unexpected exception has been caught: ' . $e->getMessage()); return false; } return $phpcsFile; }
/** * @SuppressWarnings(PHPMD.StaticAccess) */ protected function processConfig() { foreach ($this->getConfig() as $key => $value) { switch ($key) { case 'presets': case 'files': continue 2; case 'default_standard': if (is_array($value)) { $value = implode(',', $value); } } \PHP_CodeSniffer::setConfigData($key, $value, true); } }
/** * Add all sniff unit tests into a test suite. * * Sniff unit tests are found by recursing through the 'Tests' directory * of each installed coding standard. * * @return PHPUnit_Framework_TestSuite */ public static function suite() { $suite = new PHPUnit_Framework_TestSuite('PHP CodeSniffer Standards'); $baseDir = pathinfo(getcwd() . "/Ongr", PATHINFO_DIRNAME); \PHP_CodeSniffer::setConfigData('installed_paths', $baseDir); $path = pathinfo(\PHP_CodeSniffer::getInstalledStandardPath('Ongr'), PATHINFO_DIRNAME); $testsDir = $path . DIRECTORY_SEPARATOR . 'Tests' . DIRECTORY_SEPARATOR . 'Unit'; $directoryIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($testsDir)); /** @var \SplFileInfo $fileinfo */ foreach ($directoryIterator as $file) { // Skip hidden and extension must be php. if ($file->getFilename()[0] === '.' || pathinfo($file, PATHINFO_EXTENSION) !== 'php') { continue; } $className = str_replace([$baseDir . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], ['', '\\'], substr($file, 0, -4)); $suite->addTest(new $className('getErrorList')); } return $suite; }
/** * Processes a long (--example) command line argument. * * @param string $arg The command line argument. * @param int $pos The position of the argument on the command line. * @param array $values An array of values determined from CLI args. * * @return array The updated CLI values. * @see getCommandLineValues() */ public function processLongArgument($arg, $pos, $values) { switch ($arg) { case 'help': $this->printUsage(); exit(0); break; case 'version': echo 'PHP_CodeSniffer version 1.3.5 (stable) '; echo 'by Squiz Pty Ltd. (http://www.squiz.net)' . PHP_EOL; exit(0); break; case 'config-set': $key = $_SERVER['argv'][$pos + 1]; $value = $_SERVER['argv'][$pos + 2]; PHP_CodeSniffer::setConfigData($key, $value); exit(0); break; case 'config-delete': $key = $_SERVER['argv'][$pos + 1]; PHP_CodeSniffer::setConfigData($key, null); exit(0); break; case 'config-show': $data = PHP_CodeSniffer::getAllConfigData(); print_r($data); exit(0); break; default: if (substr($arg, 0, 7) === 'sniffs=') { $values['sniffs'] = array(); $sniffs = substr($arg, 7); $sniffs = explode(',', $sniffs); // Convert the sniffs to class names. foreach ($sniffs as $sniff) { $parts = explode('.', $sniff); $values['sniffs'][] = $parts[0] . '_Sniffs_' . $parts[1] . '_' . $parts[2] . 'Sniff'; } } else { if (substr($arg, 0, 12) === 'report-file=') { $values['reportFile'] = realpath(substr($arg, 12)); // It may not exist and return false instead. if ($values['reportFile'] === false) { $values['reportFile'] = substr($arg, 12); } if (is_dir($values['reportFile']) === true) { echo 'ERROR: The specified report file path "' . $values['reportFile'] . '" is a directory.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } $dir = dirname($values['reportFile']); if (is_dir($dir) === false) { echo 'ERROR: The specified report file path "' . $values['reportFile'] . '" points to a non-existent directory.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } } else { if (substr($arg, 0, 13) === 'report-width=') { $values['reportWidth'] = (int) substr($arg, 13); } else { if (substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-') { if ($arg[6] === '-') { // This is a report with file output. $split = strpos($arg, '='); if ($split === false) { $report = substr($arg, 7); $output = null; } else { $report = substr($arg, 7, $split - 7); $output = substr($arg, $split + 1); if ($output === false) { $output = null; } } } else { // This is a single report. $report = substr($arg, 7); $output = null; } $validReports = array('full', 'xml', 'checkstyle', 'csv', 'emacs', 'source', 'summary', 'svnblame', 'gitblame', 'hgblame'); if (in_array($report, $validReports) === false) { echo 'ERROR: Report type "' . $report . '" not known.' . PHP_EOL; exit(2); } $values['reports'][$report] = $output; } else { if (substr($arg, 0, 9) === 'standard=') { $values['standard'] = substr($arg, 9); } else { if (substr($arg, 0, 11) === 'extensions=') { $values['extensions'] = explode(',', substr($arg, 11)); } else { if (substr($arg, 0, 9) === 'severity=') { $values['errorSeverity'] = (int) substr($arg, 9); $values['warningSeverity'] = $values['errorSeverity']; } else { if (substr($arg, 0, 15) === 'error-severity=') { $values['errorSeverity'] = (int) substr($arg, 15); } else { if (substr($arg, 0, 17) === 'warning-severity=') { $values['warningSeverity'] = (int) substr($arg, 17); } else { if (substr($arg, 0, 7) === 'ignore=') { // Split the ignore string on commas, unless the comma is escaped // using 1 or 3 slashes (\, or \\\,). $values['ignored'] = preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 7)); } else { if (substr($arg, 0, 10) === 'generator=') { $values['generator'] = substr($arg, 10); } else { if (substr($arg, 0, 9) === 'encoding=') { $values['encoding'] = strtolower(substr($arg, 9)); } else { if (substr($arg, 0, 10) === 'tab-width=') { $values['tabWidth'] = (int) substr($arg, 10); } else { $values = $this->processUnknownArgument('--' . $arg, $pos, $values); } } } } } } } } } } } } } //end if break; } //end switch return $values; }
/** * Processes a long (--example) command line argument. * * @param string $arg The command line argument. * @param int $pos The position of the argument on the command line. * * @return void */ public function processLongArgument($arg, $pos) { switch ($arg) { case 'help': $this->printUsage(); exit(0); case 'version': echo 'PHP_CodeSniffer version ' . PHP_CodeSniffer::VERSION . ' (' . PHP_CodeSniffer::STABILITY . ') '; echo 'by Squiz (http://www.squiz.net)' . PHP_EOL; exit(0); case 'colors': $this->values['colors'] = true; break; case 'no-colors': $this->values['colors'] = false; break; case 'config-set': if (isset($this->_cliArgs[$pos + 1]) === false || isset($this->_cliArgs[$pos + 2]) === false) { echo 'ERROR: Setting a config option requires a name and value' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(0); } $key = $this->_cliArgs[$pos + 1]; $value = $this->_cliArgs[$pos + 2]; $current = PHP_CodeSniffer::getConfigData($key); try { PHP_CodeSniffer::setConfigData($key, $value); } catch (Exception $e) { echo $e->getMessage() . PHP_EOL; exit(2); } if ($current === null) { echo "Config value \"{$key}\" added successfully" . PHP_EOL; } else { echo "Config value \"{$key}\" updated successfully; old value was \"{$current}\"" . PHP_EOL; } exit(0); case 'config-delete': if (isset($this->_cliArgs[$pos + 1]) === false) { echo 'ERROR: Deleting a config option requires the name of the option' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(0); } $key = $this->_cliArgs[$pos + 1]; $current = PHP_CodeSniffer::getConfigData($key); if ($current === null) { echo "Config value \"{$key}\" has not been set" . PHP_EOL; } else { try { PHP_CodeSniffer::setConfigData($key, null); } catch (Exception $e) { echo $e->getMessage() . PHP_EOL; exit(2); } echo "Config value \"{$key}\" removed successfully; old value was \"{$current}\"" . PHP_EOL; } exit(0); case 'config-show': $data = PHP_CodeSniffer::getAllConfigData(); $this->printConfigData($data); exit(0); case 'runtime-set': if (isset($this->_cliArgs[$pos + 1]) === false || isset($this->_cliArgs[$pos + 2]) === false) { echo 'ERROR: Setting a runtime config option requires a name and value' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(0); } $key = $this->_cliArgs[$pos + 1]; $value = $this->_cliArgs[$pos + 2]; $this->_cliArgs[$pos + 1] = ''; $this->_cliArgs[$pos + 2] = ''; PHP_CodeSniffer::setConfigData($key, $value, true); break; default: if (substr($arg, 0, 7) === 'sniffs=') { $sniffs = explode(',', substr($arg, 7)); foreach ($sniffs as $sniff) { if (substr_count($sniff, '.') !== 2) { echo 'ERROR: The specified sniff code "' . $sniff . '" is invalid' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } } $this->values['sniffs'] = $sniffs; } else { if (substr($arg, 0, 10) === 'bootstrap=') { $files = explode(',', substr($arg, 10)); foreach ($files as $file) { $path = PHP_CodeSniffer::realpath($file); if ($path === false) { echo 'ERROR: The specified bootstrap file "' . $file . '" does not exist' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } $this->values['bootstrap'][] = $path; } } else { if (substr($arg, 0, 12) === 'report-file=') { $this->values['reportFile'] = PHP_CodeSniffer::realpath(substr($arg, 12)); // It may not exist and return false instead. if ($this->values['reportFile'] === false) { $this->values['reportFile'] = substr($arg, 12); $dir = dirname($this->values['reportFile']); if (is_dir($dir) === false) { echo 'ERROR: The specified report file path "' . $this->values['reportFile'] . '" points to a non-existent directory' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } if ($dir === '.') { // Passed report file is a file in the current directory. $this->values['reportFile'] = getcwd() . '/' . basename($this->values['reportFile']); } else { $dir = PHP_CodeSniffer::realpath(getcwd() . '/' . $dir); if ($dir !== false) { // Report file path is relative. $this->values['reportFile'] = $dir . '/' . basename($this->values['reportFile']); } } } //end if if (is_dir($this->values['reportFile']) === true) { echo 'ERROR: The specified report file path "' . $this->values['reportFile'] . '" is a directory' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } } else { if (substr($arg, 0, 13) === 'report-width=') { $this->values['reportWidth'] = $this->_validateReportWidth(substr($arg, 13)); } else { if (substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-') { if ($arg[6] === '-') { // This is a report with file output. $split = strpos($arg, '='); if ($split === false) { $report = substr($arg, 7); $output = null; } else { $report = substr($arg, 7, $split - 7); $output = substr($arg, $split + 1); if ($output === false) { $output = null; } else { $dir = dirname($output); if ($dir === '.') { // Passed report file is a filename in the current directory. $output = getcwd() . '/' . basename($output); } else { $dir = PHP_CodeSniffer::realpath(getcwd() . '/' . $dir); if ($dir !== false) { // Report file path is relative. $output = $dir . '/' . basename($output); } } } //end if } //end if } else { // This is a single report. $report = substr($arg, 7); $output = null; } //end if $this->values['reports'][$report] = $output; } else { if (substr($arg, 0, 9) === 'standard=') { $standards = trim(substr($arg, 9)); if ($standards !== '') { $this->values['standard'] = explode(',', $standards); } } else { if (substr($arg, 0, 11) === 'extensions=') { $this->values['extensions'] = array_merge($this->values['extensions'], explode(',', substr($arg, 11))); } else { if (substr($arg, 0, 9) === 'severity=') { $this->values['errorSeverity'] = (int) substr($arg, 9); $this->values['warningSeverity'] = $this->values['errorSeverity']; } else { if (substr($arg, 0, 15) === 'error-severity=') { $this->values['errorSeverity'] = (int) substr($arg, 15); } else { if (substr($arg, 0, 17) === 'warning-severity=') { $this->values['warningSeverity'] = (int) substr($arg, 17); } else { if (substr($arg, 0, 7) === 'ignore=') { // Split the ignore string on commas, unless the comma is escaped // using 1 or 3 slashes (\, or \\\,). $ignored = preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 7)); foreach ($ignored as $pattern) { $pattern = trim($pattern); if ($pattern === '') { continue; } $this->values['ignored'][$pattern] = 'absolute'; } } else { if (substr($arg, 0, 10) === 'generator=') { $this->values['generator'] = substr($arg, 10); } else { if (substr($arg, 0, 9) === 'encoding=') { $this->values['encoding'] = strtolower(substr($arg, 9)); } else { if (substr($arg, 0, 10) === 'tab-width=') { $this->values['tabWidth'] = (int) substr($arg, 10); } else { if ($this->dieOnUnknownArg === false) { $eqPos = strpos($arg, '='); if ($eqPos === false) { $this->values[$arg] = $arg; } else { $value = substr($arg, $eqPos + 1); $arg = substr($arg, 0, $eqPos); $this->values[$arg] = $value; } } else { $this->processUnknownArgument('--' . $arg, $pos); } } } } } } } } } } } } } } } //end if break; } //end switch }
/** * Executes PHP code sniffer against PhingFile or a FileSet */ public function main() { if (!class_exists('PHP_CodeSniffer')) { @(include_once 'PHP/CodeSniffer.php'); if (!class_exists('PHP_CodeSniffer')) { throw new BuildException("This task requires the PHP_CodeSniffer package installed and available on the include path", $this->getLocation()); } } /** * Determine PHP_CodeSniffer version number */ if (!$this->skipVersionCheck) { preg_match('/\\d\\.\\d\\.\\d/', shell_exec('phpcs --version'), $version); if (version_compare($version[0], '1.2.2') < 0) { throw new BuildException('PhpCodeSnifferTask requires PHP_CodeSniffer version >= 1.2.2', $this->getLocation()); } } if (!isset($this->file) and count($this->filesets) == 0) { throw new BuildException("Missing either a nested fileset or attribute 'file' set"); } if (PHP_CodeSniffer::isInstalledStandard($this->standard) === false) { // They didn't select a valid coding standard, so help them // out by letting them know which standards are installed. $installedStandards = PHP_CodeSniffer::getInstalledStandards(); $numStandards = count($installedStandards); $errMsg = ''; if ($numStandards === 0) { $errMsg = 'No coding standards are installed.'; } else { $lastStandard = array_pop($installedStandards); if ($numStandards === 1) { $errMsg = 'The only coding standard installed is ' . $lastStandard; } else { $standardList = implode(', ', $installedStandards); $standardList .= ' and ' . $lastStandard; $errMsg = 'The installed coding standards are ' . $standardList; } } throw new BuildException('ERROR: the "' . $this->standard . '" coding standard is not installed. ' . $errMsg, $this->getLocation()); } if (count($this->formatters) == 0) { // turn legacy format attribute into formatter $fmt = new PhpCodeSnifferTask_FormatterElement(); $fmt->setType($this->format); $fmt->setUseFile(false); $this->formatters[] = $fmt; } if (!isset($this->file)) { $fileList = array(); $project = $this->getProject(); foreach ($this->filesets as $fs) { $ds = $fs->getDirectoryScanner($project); $files = $ds->getIncludedFiles(); $dir = $fs->getDir($this->project)->getAbsolutePath(); foreach ($files as $file) { $fileList[] = $dir . DIRECTORY_SEPARATOR . $file; } } } $cwd = getcwd(); // Save command line arguments because it confuses PHPCS (version 1.3.0) $oldArgs = $_SERVER['argv']; $_SERVER['argv'] = array(); $_SERVER['argc'] = 0; $codeSniffer = new PHP_CodeSniffer($this->verbosity, $this->tabWidth, $this->encoding); $codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions); if (is_array($this->ignorePatterns)) { $codeSniffer->setIgnorePatterns($this->ignorePatterns); } foreach ($this->configData as $configData) { $codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true); } if ($this->file instanceof PhingFile) { $codeSniffer->process($this->file->getPath(), $this->standard, $this->sniffs, $this->noSubdirectories); } else { $codeSniffer->process($fileList, $this->standard, $this->sniffs, $this->noSubdirectories); } // Restore command line arguments $_SERVER['argv'] = $oldArgs; $_SERVER['argc'] = count($oldArgs); chdir($cwd); $report = $this->printErrorReport($codeSniffer); // generate the documentation if ($this->docGenerator !== '' && $this->docFile !== null) { ob_start(); $codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator); $output = ob_get_contents(); ob_end_clean(); // write to file $outputFile = $this->docFile->getPath(); $check = file_put_contents($outputFile, $output); if (is_bool($check) && !$check) { throw new BuildException('Error writing doc to ' . $outputFile); } } elseif ($this->docGenerator !== '' && $this->docFile === null) { $codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator); } if ($this->haltonerror && $report['totals']['errors'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['errors'] . ' error' . ($report['totals']['errors'] > 1 ? 's' : '')); } if ($this->haltonwarning && $report['totals']['warnings'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['warnings'] . ' warning' . ($report['totals']['warnings'] > 1 ? 's' : '')); } }
/** * Executes PHP code sniffer against PhingFile or a FileSet */ public function main() { if (!class_exists('PHP_CodeSniffer')) { include_once 'PHP/CodeSniffer.php'; } if (!isset($this->file) and count($this->filesets) == 0) { throw new BuildException("Missing either a nested fileset or attribute 'file' set"); } if (count($this->formatters) == 0) { // turn legacy format attribute into formatter $fmt = new PhpCodeSnifferTask_FormatterElement(); $fmt->setType($this->format); $fmt->setUseFile(false); $this->formatters[] = $fmt; } if (!isset($this->file)) { $fileList = array(); $project = $this->getProject(); foreach ($this->filesets as $fs) { $ds = $fs->getDirectoryScanner($project); $files = $ds->getIncludedFiles(); $dir = $fs->getDir($this->project)->getAbsolutePath(); foreach ($files as $file) { $fileList[] = $dir . DIRECTORY_SEPARATOR . $file; } } } $codeSniffer = new PHP_CodeSniffer($this->verbosity, $this->tabWidth); $codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions); if (is_array($this->ignorePatterns)) { $codeSniffer->setIgnorePatterns($this->ignorePatterns); } foreach ($this->configData as $configData) { $codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true); } if ($this->file instanceof PhingFile) { $codeSniffer->process($this->file->getPath(), $this->standard, $this->sniffs, $this->noSubdirectories); } else { $codeSniffer->process($fileList, $this->standard, $this->sniffs, $this->noSubdirectories); } $report = $this->printErrorReport($codeSniffer); // generate the documentation if ($this->docGenerator !== '' && $this->docFile !== null) { ob_start(); $codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator); $output = ob_get_contents(); ob_end_clean(); // write to file $outputFile = $this->docFile->getPath(); $check = file_put_contents($outputFile, $output); if (is_bool($check) && !$check) { throw new BuildException('Error writing doc to ' . $outputFile); } } elseif ($this->docGenerator !== '' && $this->docFile === null) { $codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator); } if ($this->haltonerror && $report['totals']['errors'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['errors'] . ' error' . ($report['totals']['errors'] > 1 ? 's' : '')); } if ($this->haltonwarning && $report['totals']['warnings'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['warnings'] . ' warning' . ($report['totals']['warnings'] > 1 ? 's' : '')); } }
/** * Processes a long (--example) command line argument. * * @param string $arg The command line argument. * @param int $pos The position of the argument on the command line. * @param array $values An array of values determined from CLI args. * * @return array The updated CLI values. * @see getCommandLineValues() */ public function processLongArgument($arg, $pos, $values) { switch ($arg) { case 'help': $this->printUsage(); exit(0); break; case 'version': echo 'PHP_CodeSniffer version 1.1.0 (stable) '; echo 'by Squiz Pty Ltd. (http://www.squiz.net)' . PHP_EOL; exit(0); break; case 'config-set': $key = $_SERVER['argv'][$pos + 1]; $value = $_SERVER['argv'][$pos + 2]; PHP_CodeSniffer::setConfigData($key, $value); exit(0); break; case 'config-delete': $key = $_SERVER['argv'][$pos + 1]; PHP_CodeSniffer::setConfigData($key, null); exit(0); break; case 'config-show': $data = PHP_CodeSniffer::getAllConfigData(); print_r($data); exit(0); break; default: if (substr($arg, 0, 7) === 'report=') { $values['report'] = substr($arg, 7); $validReports = array('full', 'xml', 'checkstyle', 'csv', 'summary'); if (in_array($values['report'], $validReports) === false) { echo 'ERROR: Report type "' . $report . '" not known.' . PHP_EOL; exit(2); } } else { if (substr($arg, 0, 9) === 'standard=') { $values['standard'] = substr($arg, 9); } else { if (substr($arg, 0, 11) === 'extensions=') { $values['extensions'] = explode(',', substr($arg, 11)); } else { if (substr($arg, 0, 7) === 'ignore=') { // Split the ignore string on commas, unless the comma is escaped // using 1 or 3 slashes (\, or \\\,). $values['ignored'] = preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 7)); } else { if (substr($arg, 0, 10) === 'generator=') { $values['generator'] = substr($arg, 10); } else { if (substr($arg, 0, 10) === 'tab-width=') { $values['tabWidth'] = (int) substr($arg, 10); } else { $values = $this->processUnknownArgument('--' . $arg, $values); } } } } } } //end if break; } //end switch return $values; }
/** * Executes PHP code sniffer against PhingFile or a FileSet */ public function main() { if (!class_exists('PHP_CodeSniffer')) { include_once 'PHP/CodeSniffer.php'; } /** * Determine PHP_CodeSniffer version number */ if (!$this->skipVersionCheck) { preg_match('/\\d\\.\\d\\.\\d/', shell_exec('phpcs --version'), $version); if (version_compare($version[0], '1.2.2') < 0) { throw new BuildException('PhpCodeSnifferTask requires PHP_CodeSniffer version >= 1.2.2', $this->getLocation()); } } if (!isset($this->file) and count($this->filesets) == 0) { throw new BuildException("Missing either a nested fileset or attribute 'file' set"); } if (count($this->formatters) == 0) { // turn legacy format attribute into formatter $fmt = new PhpCodeSnifferTask_FormatterElement(); $fmt->setType($this->format); $fmt->setUseFile(false); $this->formatters[] = $fmt; } if (!isset($this->file)) { $fileList = array(); $project = $this->getProject(); foreach ($this->filesets as $fs) { $ds = $fs->getDirectoryScanner($project); $files = $ds->getIncludedFiles(); $dir = $fs->getDir($this->project)->getAbsolutePath(); foreach ($files as $file) { $fileList[] = $dir . DIRECTORY_SEPARATOR . $file; } } } $cwd = getcwd(); // Save command line arguments because it confuses PHPCS (version 1.3.0) $oldArgs = $_SERVER['argv']; $_SERVER['argv'] = array(); $codeSniffer = new PHP_CodeSniffer($this->verbosity, $this->tabWidth); $codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions); if (is_array($this->ignorePatterns)) { $codeSniffer->setIgnorePatterns($this->ignorePatterns); } foreach ($this->configData as $configData) { $codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true); } if ($this->file instanceof PhingFile) { $codeSniffer->process($this->file->getPath(), $this->standard, $this->sniffs, $this->noSubdirectories); } else { $codeSniffer->process($fileList, $this->standard, $this->sniffs, $this->noSubdirectories); } // Restore command line arguments $_SERVER['argv'] = $oldArgs; chdir($cwd); $report = $this->printErrorReport($codeSniffer); // generate the documentation if ($this->docGenerator !== '' && $this->docFile !== null) { ob_start(); $codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator); $output = ob_get_contents(); ob_end_clean(); // write to file $outputFile = $this->docFile->getPath(); $check = file_put_contents($outputFile, $output); if (is_bool($check) && !$check) { throw new BuildException('Error writing doc to ' . $outputFile); } } elseif ($this->docGenerator !== '' && $this->docFile === null) { $codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator); } if ($this->haltonerror && $report['totals']['errors'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['errors'] . ' error' . ($report['totals']['errors'] > 1 ? 's' : '')); } if ($this->haltonwarning && $report['totals']['warnings'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['warnings'] . ' warning' . ($report['totals']['warnings'] > 1 ? 's' : '')); } }
/** * Processes a long (--example) command line argument. * * @param string $arg The command line argument. * @param int $pos The position of the argument on the command line. * * @return void */ public function processLongArgument($arg, $pos) { switch ($arg) { case 'help': $this->printUsage(); exit(0); case 'version': echo 'PHP_CodeSniffer version ' . PHP_CodeSniffer::VERSION . ' (' . PHP_CodeSniffer::STABILITY . ') '; echo 'by Squiz (http://www.squiz.net)' . PHP_EOL; exit(0); case 'config-set': $key = $this->_cliArgs[$pos + 1]; $value = $this->_cliArgs[$pos + 2]; PHP_CodeSniffer::setConfigData($key, $value); exit(0); case 'config-delete': $key = $this->_cliArgs[$pos + 1]; PHP_CodeSniffer::setConfigData($key, null); exit(0); case 'config-show': $data = PHP_CodeSniffer::getAllConfigData(); print_r($data); exit(0); case 'runtime-set': $key = $this->_cliArgs[$pos + 1]; $value = $this->_cliArgs[$pos + 2]; $this->_cliArgs[$pos + 1] = ''; $this->_cliArgs[$pos + 2] = ''; PHP_CodeSniffer::setConfigData($key, $value, true); break; default: if (substr($arg, 0, 7) === 'sniffs=') { $sniffs = substr($arg, 7); $this->values['sniffs'] = explode(',', $sniffs); } else { if (substr($arg, 0, 12) === 'report-file=') { $this->values['reportFile'] = PHP_CodeSniffer::realpath(substr($arg, 12)); // It may not exist and return false instead. if ($this->values['reportFile'] === false) { $this->values['reportFile'] = substr($arg, 12); } if (is_dir($this->values['reportFile']) === true) { echo 'ERROR: The specified report file path "' . $this->values['reportFile'] . '" is a directory.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } $dir = dirname($this->values['reportFile']); if (is_dir($dir) === false) { echo 'ERROR: The specified report file path "' . $this->values['reportFile'] . '" points to a non-existent directory.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } if ($dir === '.') { // Passed report file is a filename in the current directory. $this->values['reportFile'] = getcwd() . '/' . basename($this->values['reportFile']); } else { $dir = PHP_CodeSniffer::realpath(getcwd() . '/' . $dir); if ($dir !== false) { // Report file path is relative. $this->values['reportFile'] = $dir . '/' . basename($this->values['reportFile']); } } } else { if (substr($arg, 0, 13) === 'report-width=') { $this->values['reportWidth'] = (int) substr($arg, 13); } else { if (substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-') { if ($arg[6] === '-') { // This is a report with file output. $split = strpos($arg, '='); if ($split === false) { $report = substr($arg, 7); $output = null; } else { $report = substr($arg, 7, $split - 7); $output = substr($arg, $split + 1); if ($output === false) { $output = null; } else { $dir = dirname($output); if ($dir === '.') { // Passed report file is a filename in the current directory. $output = getcwd() . '/' . basename($output); } else { $dir = PHP_CodeSniffer::realpath(getcwd() . '/' . $dir); if ($dir !== false) { // Report file path is relative. $output = $dir . '/' . basename($output); } } } //end if } //end if } else { // This is a single report. $report = substr($arg, 7); $output = null; } //end if $this->values['reports'][$report] = $output; } else { if (substr($arg, 0, 9) === 'standard=') { $standards = trim(substr($arg, 9)); if ($standards !== '') { $this->values['standard'] = explode(',', $standards); } } else { if (substr($arg, 0, 11) === 'extensions=') { $this->values['extensions'] = explode(',', substr($arg, 11)); } else { if (substr($arg, 0, 9) === 'severity=') { $this->values['errorSeverity'] = (int) substr($arg, 9); $this->values['warningSeverity'] = $this->values['errorSeverity']; } else { if (substr($arg, 0, 15) === 'error-severity=') { $this->values['errorSeverity'] = (int) substr($arg, 15); } else { if (substr($arg, 0, 17) === 'warning-severity=') { $this->values['warningSeverity'] = (int) substr($arg, 17); } else { if (substr($arg, 0, 7) === 'ignore=') { // Split the ignore string on commas, unless the comma is escaped // using 1 or 3 slashes (\, or \\\,). $ignored = preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 7)); foreach ($ignored as $pattern) { $pattern = trim($pattern); if ($pattern == '') { continue; } $this->values['ignored'][$pattern] = 'absolute'; } } else { if (substr($arg, 0, 10) === 'generator=') { $this->values['generator'] = substr($arg, 10); } else { if (substr($arg, 0, 9) === 'encoding=') { $this->values['encoding'] = strtolower(substr($arg, 9)); } else { if (substr($arg, 0, 10) === 'tab-width=') { $this->values['tabWidth'] = (int) substr($arg, 10); } else { if ($this->dieOnUnknownArg === false) { $eqPos = strpos($arg, '='); if ($eqPos === false) { $this->values[$arg] = $arg; } else { $value = substr($arg, $eqPos + 1); $arg = substr($arg, 0, $eqPos); $this->values[$arg] = $value; } } else { echo 'ERROR: option "' . $arg . '" not known.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } } } } } } } } } } } } } } //end if break; } //end switch }
/** * Processes a long (--example) command line argument. * * @param string $arg The command line argument. * @param int $pos The position of the argument on the command line. * @param array $values An array of values determined from CLI args. * * @return array The updated CLI values. * @see getCommandLineValues() */ public function processLongArgument($arg, $pos, $values) { switch ($arg) { case 'help': $this->printUsage(); exit(0); case 'version': echo 'PHP_CodeSniffer version ' . PHP_CodeSniffer::VERSION . ' (' . PHP_CodeSniffer::STABILITY . ') '; echo 'by Squiz (http://www.squiz.net)' . PHP_EOL; exit(0); case 'config-set': $key = $_SERVER['argv'][$pos + 1]; $value = $_SERVER['argv'][$pos + 2]; $current = PHP_CodeSniffer::getConfigData($key); try { PHP_CodeSniffer::setConfigData($key, $value); } catch (Exception $e) { echo $e->getMessage() . PHP_EOL; exit(2); } if ($current === null) { echo "Config value \"{$key}\" added successfully" . PHP_EOL; } else { echo "Config value \"{$key}\" updated successfully; old value was \"{$current}\"" . PHP_EOL; } exit(0); case 'config-delete': $key = $_SERVER['argv'][$pos + 1]; $current = PHP_CodeSniffer::getConfigData($key); if ($current === null) { echo "Config value \"{$key}\" has not been set" . PHP_EOL; } else { try { PHP_CodeSniffer::setConfigData($key, null); } catch (Exception $e) { echo $e->getMessage() . PHP_EOL; exit(2); } echo "Config value \"{$key}\" removed successfully; old value was \"{$current}\"" . PHP_EOL; } exit(0); case 'config-show': $data = PHP_CodeSniffer::getAllConfigData(); $this->printConfigData($data); exit(0); case 'runtime-set': $key = $_SERVER['argv'][$pos + 1]; $value = $_SERVER['argv'][$pos + 2]; $_SERVER['argv'][$pos + 1] = ''; $_SERVER['argv'][$pos + 2] = ''; PHP_CodeSniffer::setConfigData($key, $value, true); break; default: if (substr($arg, 0, 7) === 'sniffs=') { $sniffs = explode(',', substr($arg, 7)); foreach ($sniffs as $sniff) { if (substr_count($sniff, '.') !== 2) { echo 'ERROR: The specified sniff code "' . $sniff . '" is invalid.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } } $values['sniffs'] = $sniffs; } else { if (substr($arg, 0, 12) === 'report-file=') { $values['reportFile'] = realpath(substr($arg, 12)); // It may not exist and return false instead. if ($values['reportFile'] === false) { $values['reportFile'] = substr($arg, 12); } if (is_dir($values['reportFile']) === true) { echo 'ERROR: The specified report file path "' . $values['reportFile'] . '" is a directory.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } $dir = dirname($values['reportFile']); if (is_dir($dir) === false) { echo 'ERROR: The specified report file path "' . $values['reportFile'] . '" points to a non-existent directory.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } if ($dir === '.') { // Passed report file is a filename in the current directory. $values['reportFile'] = getcwd() . '/' . basename($values['reportFile']); } else { $dir = realpath(getcwd() . '/' . $dir); if ($dir !== false) { // Report file path is relative. $values['reportFile'] = $dir . '/' . basename($values['reportFile']); } } } else { if (substr($arg, 0, 13) === 'report-width=') { $values['reportWidth'] = (int) substr($arg, 13); } else { if (substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-') { if ($arg[6] === '-') { // This is a report with file output. $split = strpos($arg, '='); if ($split === false) { $report = substr($arg, 7); $output = null; } else { $report = substr($arg, 7, $split - 7); $output = substr($arg, $split + 1); if ($output === false) { $output = null; } else { $dir = dirname($output); if ($dir === '.') { // Passed report file is a filename in the current directory. $output = getcwd() . '/' . basename($output); } else { $dir = realpath(getcwd() . '/' . $dir); if ($dir !== false) { // Report file path is relative. $output = $dir . '/' . basename($output); } } } //end if } //end if } else { // This is a single report. $report = substr($arg, 7); $output = null; } $validReports = array('full', 'xml', 'json', 'checkstyle', 'junit', 'csv', 'emacs', 'notifysend', 'source', 'summary', 'svnblame', 'gitblame', 'hgblame'); if (in_array($report, $validReports) === false) { echo 'ERROR: Report type "' . $report . '" not known.' . PHP_EOL; exit(2); } $values['reports'][$report] = $output; } else { if (substr($arg, 0, 9) === 'standard=') { $values['standard'] = explode(',', substr($arg, 9)); } else { if (substr($arg, 0, 11) === 'extensions=') { $values['extensions'] = explode(',', substr($arg, 11)); } else { if (substr($arg, 0, 9) === 'severity=') { $values['errorSeverity'] = (int) substr($arg, 9); $values['warningSeverity'] = $values['errorSeverity']; } else { if (substr($arg, 0, 15) === 'error-severity=') { $values['errorSeverity'] = (int) substr($arg, 15); } else { if (substr($arg, 0, 17) === 'warning-severity=') { $values['warningSeverity'] = (int) substr($arg, 17); } else { if (substr($arg, 0, 7) === 'ignore=') { // Split the ignore string on commas, unless the comma is escaped // using 1 or 3 slashes (\, or \\\,). $ignored = preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 7)); foreach ($ignored as $pattern) { $values['ignored'][$pattern] = 'absolute'; } } else { if (substr($arg, 0, 10) === 'generator=') { $values['generator'] = substr($arg, 10); } else { if (substr($arg, 0, 9) === 'encoding=') { $values['encoding'] = strtolower(substr($arg, 9)); } else { if (substr($arg, 0, 10) === 'tab-width=') { $values['tabWidth'] = (int) substr($arg, 10); } else { $values = $this->processUnknownArgument('--' . $arg, $pos, $values); } } } } } } } } } } } } } //end if break; } //end switch return $values; }
/** * Executes PHP code sniffer against PhingFile or a FileSet */ public function main() { if (!isset($this->file) and count($this->filesets) == 0) { throw new BuildException("Missing either a nested fileset or attribute 'file' set"); } require_once 'PHP/CodeSniffer.php'; $codeSniffer = new PHP_CodeSniffer($this->verbosity, $this->tabWidth); $codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions); if (is_array($this->ignorePatterns)) { $codeSniffer->setIgnorePatterns($this->ignorePatterns); } foreach ($this->configData as $configData) { $codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true); } if ($this->file instanceof PhingFile) { $codeSniffer->process($this->file->getPath(), $this->standard, $this->sniffs, $this->noSubdirectories); } else { $fileList = array(); $project = $this->getProject(); foreach ($this->filesets as $fs) { $ds = $fs->getDirectoryScanner($project); $files = $ds->getIncludedFiles(); $dir = $fs->getDir($this->project)->getPath(); foreach ($files as $file) { $fileList[] = $dir . DIRECTORY_SEPARATOR . $file; } } $codeSniffer->process($fileList, $this->standard, $this->sniffs, $this->noSubdirectories); } $this->output($codeSniffer); }
/** * Executes PHP code sniffer against PhingFile or a FileSet */ public function main() { if (!isset($this->file) and count($this->filesets) == 0) { throw new BuildException("Missing either a nested fileset or attribute 'file' set"); } if (count($this->formatters) == 0) { // turn legacy format attribute into formatter $fmt = new PhpCodeSnifferTask_FormatterElement(); $fmt->setType($this->format); $fmt->setUseFile(false); $this->formatters[] = $fmt; } if (!isset($this->file)) { $fileList = array(); $project = $this->getProject(); foreach ($this->filesets as $fs) { $ds = $fs->getDirectoryScanner($project); $files = $ds->getIncludedFiles(); $dir = $fs->getDir($this->project)->getAbsolutePath(); foreach ($files as $file) { $fileList[] = $dir . DIRECTORY_SEPARATOR . $file; } } } /* save current directory */ $old_cwd = getcwd(); require_once 'PHP/CodeSniffer.php'; $codeSniffer = new PHP_CodeSniffer($this->verbosity, $this->tabWidth); $codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions); if (is_array($this->ignorePatterns)) { $codeSniffer->setIgnorePatterns($this->ignorePatterns); } foreach ($this->configData as $configData) { $codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true); } if ($this->file instanceof PhingFile) { $codeSniffer->process($this->file->getPath(), $this->standard, $this->sniffs, $this->noSubdirectories); } else { $codeSniffer->process($fileList, $this->standard, $this->sniffs, $this->noSubdirectories); } $this->output($codeSniffer); $report = $codeSniffer->prepareErrorReport(true); if ($this->haltonerror && $report['totals']['errors'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['errors'] . ' error' . ($report['totals']['errors'] > 1 ? 's' : '')); } if ($this->haltonwarning && $report['totals']['warnings'] > 0) { throw new BuildException('phpcodesniffer detected ' . $report['totals']['warnings'] . ' warning' . ($report['totals']['warnings'] > 1 ? 's' : '')); } /* reset current directory */ chdir($old_cwd); }