/** * 実行 * * @param string $path パス * * @return void */ public static function process($path) { require_once 'PHP/CodeSniffer.php'; require_once 'PHP/CodeSniffer/Reports/Full.php'; $phpcs = new PHP_CodeSniffer(); try { $phpcs->process($path, 'BEAR'); echo "<pre><code>"; echo "<div class='info'>BEAR Convention</div>"; $fileViolations = $phpcs->getFilesErrors(); $report = new PHP_CodeSniffer_Reporting(); $report->printReport('Summary', $fileViolations, true, null, 120); $report->printReport('Full', $fileViolations, false, null, 120); echo "</code></pre>"; } catch (Exception $e) { echo $e->getMessage(); } }
/** * Run the code sniffs over a single given file. * * Processes the file and runs the PHP_CodeSniffer sniffs to verify that it * conforms with the standard. Returns the processed file object, or NULL * if no file was processed due to error. * * @param string $file The file to process. * @param string $contents The contents to parse. If NULL, the content * is taken from the file system. * * @return PHP_CodeSniffer_File * @throws PHP_CodeSniffer_Exception If the file could not be processed. * @see _processFile() */ public function processFile($file, $contents = null) { if ($contents === null && file_exists($file) === false) { throw new PHP_CodeSniffer_Exception("Source file {$file} does not exist"); } $filePath = realpath($file); if ($filePath === false) { $filePath = $file; } // Before we go and spend time tokenizing this file, just check // to see if there is a tag up top to indicate that the whole // file should be ignored. It must be on one of the first two lines. $firstContent = $contents; if ($contents === null && is_readable($filePath) === true) { $handle = fopen($filePath, 'r'); if ($handle !== false) { $firstContent = fgets($handle); $firstContent .= fgets($handle); fclose($handle); } } if (strpos($firstContent, '@codingStandardsIgnoreFile') !== false) { // We are ignoring the whole file. if (PHP_CODESNIFFER_VERBOSITY > 0) { echo 'Ignoring ' . basename($filePath) . PHP_EOL; } return null; } try { $phpcsFile = $this->_processFile($file, $contents); } catch (Exception $e) { $trace = $e->getTrace(); $filename = $trace[0]['args'][0]; if (is_object($filename) === true && get_class($filename) === 'PHP_CodeSniffer_File') { $filename = $filename->getFilename(); } else { if (is_numeric($filename) === true) { // See if we can find the PHP_CodeSniffer_File object. foreach ($trace as $data) { if (isset($data['args'][0]) === true && $data['args'][0] instanceof PHP_CodeSniffer_File === true) { $filename = $data['args'][0]->getFilename(); } } } else { if (is_string($filename) === false) { $filename = (string) $filename; } } } $error = 'An error occurred during processing; checking has been aborted. The error message was: ' . $e->getMessage(); $phpcsFile = new PHP_CodeSniffer_File($filename, $this->listeners, $this->allowedFileExtensions, $this->ruleset, $this); $this->addFile($phpcsFile); $phpcsFile->addError($error, null); } //end try if (PHP_CODESNIFFER_INTERACTIVE === false) { return $phpcsFile; } /* Running interactively. Print the error report for the current file and then wait for user input. */ $reporting = new PHP_CodeSniffer_Reporting(); $cliValues = $this->cli->getCommandLineValues(); // Get current violations and then clear the list to make sure // we only print violations for a single file each time. $numErrors = null; while ($numErrors !== 0) { $filesViolations = $this->getFilesErrors(); $this->files = array(); $numErrors = $reporting->printReport('full', $filesViolations, $cliValues['showSources'], null, $cliValues['reportWidth']); if ($numErrors === 0) { continue; } echo '<ENTER> to recheck, [s] to skip or [q] to quit : '; $input = fgets(STDIN); $input = trim($input); switch ($input) { case 's': break; case 'q': exit(0); break; default: // Repopulate the sniffs because some of them save their state // and only clear it when the file changes, but we are rechecking // the same file. $this->populateTokenListeners(); $phpcsFile = $this->_processFile($file, $contents); break; } } //end while return $phpcsFile; }
/** * Prints the error report for the run. * * Note that this function may actually print multiple reports * as the user may have specified a number of output formats. * * @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing * the errors. * @param array $reports A list of reports to print. * @param bool $showSources TRUE if report should show error sources * (not used by all reports). * @param string $reportFile A default file to log report output to. * @param int $reportWidth How wide the screen reports should be. * * @return int The number of error and warning messages shown. */ public function printErrorReport(PHP_CodeSniffer $phpcs, $reports, $showSources, $reportFile, $reportWidth) { $reporting = new PHP_CodeSniffer_Reporting(); $filesViolations = $phpcs->getFilesErrors(); if (empty($reports) === true) { $reports['full'] = $reportFile; } $errors = 0; $toScreen = false; foreach ($reports as $report => $output) { if ($output === null) { $output = $reportFile; } if ($reportFile === null) { $toScreen = true; } // We don't add errors here because the number of // errors reported by each report type will always be the // same, so we really just need 1 number. $errors = $reporting->printReport($report, $filesViolations, $showSources, $output, $reportWidth); } // Only print PHP_Timer output if no reports were // printed to the screen so we don't put additional output // in something like an XML report. If we are printing to screen, // the report types would have already worked out who should // print the timer info. if ($toScreen === false && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) { echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL; } // They should all return the same value, so it // doesn't matter which return value we end up using. return $errors; }
/** * Prints the error report. * * @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing * the errors. * * @return int The number of error and warning messages shown. */ protected function printErrorReport($phpcs) { if ($this->showSniffs) { $sniffs = $phpcs->getSniffs(); $sniffStr = ''; foreach ($sniffs as $sniff) { $sniffStr .= '- ' . $sniff . PHP_EOL; } $this->log('The list of used sniffs (#' . count($sniffs) . '): ' . PHP_EOL . $sniffStr, Project::MSG_INFO); } $filesViolations = $phpcs->getFilesErrors(); $reporting = new PHP_CodeSniffer_Reporting(); $report = $reporting->prepare($filesViolations, $this->showWarnings); // process output foreach ($this->formatters as $fe) { switch ($fe->getType()) { case 'default': // default format goes to logs, no buffering $this->outputCustomFormat($report); $fe->setUseFile(false); break; default: $reportFile = null; if ($fe->getUseFile()) { $reportFile = $fe->getOutfile(); ob_start(); } // Determine number of parameters required to // ensure backwards compatibility $rm = new ReflectionMethod('PHP_CodeSniffer_Reporting', 'printReport'); if ($rm->getNumberOfParameters() == 5) { $reporting->printReport($fe->getType(), $filesViolations, $this->showSources, $reportFile, $this->reportWidth); } else { $reporting->printReport($fe->getType(), $filesViolations, $this->showWarnings, $this->showSources, $reportFile, $this->reportWidth); } // reporting class uses ob_end_flush(), but we don't want // an output if we use a file if ($fe->getUseFile()) { ob_end_clean(); } break; } } return $report; }
/** * Run the code sniffs over a single given file. * * Processes the file and runs the PHP_CodeSniffer sniffs to verify that it * conforms with the standard. * * @param string $file The file to process. * @param string $contents The contents to parse. If NULL, the content * is taken from the file system. * * @return void * @throws PHP_CodeSniffer_Exception If the file could not be processed. * @see _processFile() */ public function processFile($file, $contents = null) { if ($contents === null && file_exists($file) === false) { throw new PHP_CodeSniffer_Exception("Source file {$file} does not exist"); } // If the file's path matches one of our ignore patterns, skip it. foreach ($this->ignorePatterns as $pattern) { $replacements = array('\\,' => ',', '*' => '.*'); $pattern = strtr($pattern, $replacements); if (preg_match("|{$pattern}|i", $file) === 1) { return; } } // Before we go and spend time tokenizing this file, just check // to see if there is a tag up top to indicate that the whole // file should be ignored. It must be on one of the first two lines. $firstContent = $contents; if ($contents === null) { $handle = fopen($file, 'r'); if ($handle !== false) { $firstContent = fgets($handle); $firstContent .= fgets($handle); fclose($handle); } } if (strpos($firstContent, '@codingStandardsIgnoreFile') !== false) { // We are ignoring the whole file. if (PHP_CODESNIFFER_VERBOSITY > 0) { echo 'Ignoring ' . basename($file) . PHP_EOL; } return; } $this->_processFile($file, $contents); if (PHP_CODESNIFFER_INTERACTIVE === false) { return; } /* Running interactively. Print the error report for the current file and then wait for user input. */ $reporting = new PHP_CodeSniffer_Reporting(); $cliValues = $this->cli->getCommandLineValues(); // Get current violations and then clear the list to make sure // we only print violations for a single file each time. $numErrors = null; while ($numErrors !== 0) { $filesViolations = $this->getFilesErrors(); $this->files = array(); $numErrors = $reporting->printReport($cliValues['report'], $filesViolations, $cliValues['showSources'], '', $cliValues['reportWidth']); if ($numErrors === 0) { continue; } echo '<ENTER> to recheck, [s] to skip or [q] to quit : '; $input = fgets(STDIN); $input = trim($input); switch ($input) { case 's': break; case 'q': exit(0); break; default: // Repopulate the sniffs because some of them save their state // and only clear it when the file changes, but we are rechecking // the same file. $this->populateTokenListeners(); $this->_processFile($file, $contents); break; } } //end while }
* * @package local * @subpackage codechecker * @copyright 2011 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('CLI_SCRIPT', true); require dirname(__FILE__) . '/../../config.php'; require_once $CFG->libdir . '/clilib.php'; require_once $CFG->dirroot . '/local/codechecker/locallib.php'; // Get the command-line options. list($options, $unrecognized) = cli_get_params(array('help' => false), array('h' => 'help')); if (count($unrecognized) != 1) { $options['help'] = true; } else { $path = clean_param(reset($unrecognized), PARAM_PATH); } if ($options['help']) { echo get_string('clihelp', 'local_codechecker'), "\n"; die; } raise_memory_limit(MEMORY_HUGE); $standard = $CFG->dirroot . str_replace('/', DIRECTORY_SEPARATOR, '/local/codechecker/moodle'); $phpcs = new PHP_CodeSniffer(1); $phpcs->setCli(new local_codechecker_codesniffer_cli()); $phpcs->setIgnorePatterns(local_codesniffer_get_ignores()); $numerrors = $phpcs->process(local_codechecker_clean_path($CFG->dirroot . '/' . trim($path, '/')), local_codechecker_clean_path($standard)); $reporting = new PHP_CodeSniffer_Reporting(); $problems = $phpcs->getFilesErrors(); $reporting->printReport('full', $problems, false, null);
/** * Prints the error report. * * @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing * the errors. * @param string $report The type of report to print. * @param bool $showWarnings TRUE if warnings should also be printed. * @param bool $showSources TRUE if report should show error sources * (not used by all reports). * @param string $reportFile A file to log the report out to. * @param int $reportWidth How wide the screen reports should be. * * @return int The number of error and warning messages shown. */ public function printErrorReport(PHP_CodeSniffer $phpcs, $report, $showWarnings, $showSources, $reportFile, $reportWidth) { $filesViolations = $phpcs->getFilesErrors(); $reporting = new PHP_CodeSniffer_Reporting(); return $reporting->printReport($report, $filesViolations, $showWarnings, $showSources, $reportFile, $reportWidth); }
/** * Print a report into a file * * @param string $file File path * @param string $reportType One of full xml checkstyle csv emacs source summary svnblame gitblame * * @return int Error and warning count */ function report($file, $reportType = "xml") { // Create the file $reportPath = $this->makeReportPath($file, $reportType); CMbPath::forceDir(dirname($reportPath)); touch($reportPath); // Build the report $reporting = new PHP_CodeSniffer_Reporting(); return $reporting->printReport($reportType, $this->getFilesErrors(), $showSources = true, $reportPath, $reportWidth = 120); }
/** * Prints the error report. * * @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing * the errors. * * @return int The number of error and warning messages shown. */ protected function printErrorReport($phpcs) { if ($this->showSniffs) { $sniffs = $phpcs->getSniffs(); $sniffStr = ''; foreach ($sniffs as $sniff) { $sniffStr .= '- ' . $sniff . PHP_EOL; } $this->log('The list of used sniffs (#' . count($sniffs) . '): ' . PHP_EOL . $sniffStr, Project::MSG_INFO); } $filesViolations = $phpcs->getFilesErrors(); $reporting = new PHP_CodeSniffer_Reporting(); $report = $reporting->prepare($filesViolations, $this->showWarnings); // process output foreach ($this->formatters as $fe) { switch ($fe->getType()) { case 'default': // default format goes to logs, no buffering $this->outputCustomFormat($report); $fe->setUseFile(false); break; default: $reportFile = ''; if ($fe->getUseFile()) { $reportFile = $fe->getOutfile()->getPath(); ob_start(); } $reporting->printReport($fe->getType(), $filesViolations, $this->showWarnings, $this->showSources, $reportFile, $this->reportWidth); // reporting class uses ob_end_flush(), but we don't want // an output if we use a file if ($fe->getUseFile()) { ob_end_clean(); } break; } } return $report; }
/** * Execute the task * * @return self * @throw BuildException */ public function execute() { if (!$this->getStandard()) { throw new BuildException("No standard set"); } if (!class_exists("CodeSniffer")) { Pale::run(function () { require_once "PHP/CodeSniffer.php"; }); } if (CodeSniffer::isInstalledStandard($this->getStandard()) === false) { throw new BuildException("Invalid standard name"); } // Clear out argv so PHP_CodeSniffer doesn"t freak out $oldArgv = $SERVER["argv"]; $SERVER["argv"] = array(); $SERVER["argc"] = 0; // Get the current working directory because PHP_CodeSniffer will change it $cwd = getcwd(); $codeSniffer = new CodeSniffer(0, 0, "UTF-8"); $codeSniffer->process($this->getFiles(), $this->filterProperties($this->getStandard())); // Restore the argv/c superglobals $SERVER["argv"] = $oldArgv; $SERVER["argc"] = count($oldArgv); // Reset the current working directory chdir($cwd); $filesViolations = $codeSniffer->getFilesErrors(); $reporting = new Reporting(); $report = $reporting->prepare($filesViolations, $this->getShowWarnings()); $reporting->printReport($this->getReportType(), $filesViolations, $this->getShowSources(), $this->getReportFile(), $this->getReportWidth()); return $this; }
/** * Prints the error report for the run. * * Note that this function may actually print multiple reports * as the user may have specified a number of output formats. * * @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing * the errors. * @param array $reports A list of reports to print. * @param bool $showSources TRUE if report should show error sources * (not used by all reports). * @param string $reportFile A default file to log report output to. * @param int $reportWidth How wide the screen reports should be. * * @return int The number of error and warning messages shown. */ public function printErrorReport(PHP_CodeSniffer $phpcs, $reports, $showSources, $reportFile, $reportWidth) { $reporting = new PHP_CodeSniffer_Reporting(); $filesViolations = $phpcs->getFilesErrors(); if (empty($reports) === true) { $reports['full'] = $reportFile; } $errors = 0; foreach ($reports as $report => $output) { if ($output === null) { $output = $reportFile; } $errors = $reporting->printReport($report, $filesViolations, $showSources, $output, $reportWidth); } // They should all return the same value, so it // doesn't matter which return value we end up using. return $errors; }