/** * @return Result */ public function run() { $this->startTimer(); if (!isset($this->standard)) { $this->standard[] = $this->getJoomlaCodingSniffers(); } $this->printTaskInfo('Initialising CodeSniffer Checks...'); // Build the options for the sniffer $options = array('files' => $this->files, 'standard' => $this->standard, 'ignored' => $this->ignored, 'showProgress' => true, 'verbosity' => false, 'ignore_errors_on_exit' => $this->ignore_errors_on_exit); // Instantiate the sniffer $phpcs = new \PHP_CodeSniffer_CLI(); // Ensure PHPCS can run, will exit if requirements aren't met $phpcs->checkRequirements(); // Run the sniffs $numErrors = $phpcs->process($options); $this->stopTimer(); $message = 'There were no code style issues detected.'; $exitCode = 0; if ($numErrors) { $message = "There were {$numErrors} issues detected."; $exitCode = 1; } if ($this->ignore_errors_on_exit) { $exitCode = 0; } return new Result($this, $exitCode, $message, ['time' => $this->getExecutionTime()]); }
/** * (non-PHPdoc) * @see MageUC_Console_Task::execute() */ public function execute() { print '[checkstyle] Lancement du checkstyle : ' . $this->getArgument('to_check') . PHP_EOL; require_once 'PHP' . DS . 'CodeSniffer.php'; $phpcs = new PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); $phpcs->process($this->_getOptions()); print '[checkstyle] done' . PHP_EOL; }
public function testRun() { $whiteList = array('test' . rand(), 'test' . rand()); $blackList = array('test' . rand(), 'test' . rand()); $extensions = array('test' . rand(), 'test' . rand()); $this->_wrapper->expects($this->once())->method('getDefaults')->will($this->returnValue(array())); $expectedCliEmulation = array('files' => $whiteList, 'standard' => self::RULE_SET, 'ignored' => $blackList, 'extensions' => $extensions, 'reportFile' => self::REPORT_FILE, 'warningSeverity' => 0, 'reports' => array('checkstyle' => null)); $this->_wrapper->expects($this->once())->method('setValues')->with($this->equalTo($expectedCliEmulation)); $this->_wrapper->expects($this->once())->method('process'); $this->_tool->run($whiteList, $blackList, $extensions); }
public function testRun() { $whiteList = ['test' . rand(), 'test' . rand()]; $extensions = ['test' . rand(), 'test' . rand()]; $this->_wrapper->expects($this->once())->method('getDefaults')->will($this->returnValue([])); $expectedCliEmulation = ['files' => $whiteList, 'standard' => [self::RULE_SET], 'extensions' => $extensions, 'reportFile' => self::REPORT_FILE, 'warningSeverity' => 0, 'reports' => ['checkstyle' => null]]; $this->_tool->setExtensions($extensions); $this->_wrapper->expects($this->once())->method('setValues')->with($this->equalTo($expectedCliEmulation)); $this->_wrapper->expects($this->once())->method('process'); $this->_tool->run($whiteList); }
/** * Run the coding style check * * @return int */ public function process() { $this->setDefaultValues(); \PHP_CodeSniffer_Reporting::startTiming(); $phpcs = new \PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); $values = $phpcs->getCommandLineValues(); foreach ($this->defaultValues as $k => $v) { if (empty($values[$k])) { $values[$k] = $v; } } return $phpcs->process($values); }
/** * Run PHPCS on a file. * * Returns a string representation of the output that would normally * be printed to the console. Artifically sets the `-s` (showSources) * command line switch to make it possible to parse which rules failed * for a given sample file. * * @param string $file to run. * @return string The output from phpcs. */ public function runPhpCs($file) { $defaults = $this->_phpcs->getDefaults(); $standard = $this->_rootDir . '/ruleset.xml'; if (defined('PHP_CodeSniffer::VERSION') && version_compare(PHP_CodeSniffer::VERSION, '1.5.0') != -1) { $standard = [$standard]; } $options = ['encoding' => 'utf-8', 'files' => [$file], 'standard' => $standard, 'showSources' => true] + $defaults; // New PHPCS has a strange issue where the method arguments // are not stored on the instance causing weird errors. $reflection = new ReflectionProperty($this->_phpcs, 'values'); $reflection->setAccessible(true); $reflection->setValue($this->_phpcs, $options); ob_start(); $this->_phpcs->process($options); $result = ob_get_contents(); ob_end_clean(); return $result; }
/** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output * * @return int */ public function execute(InputInterface $input, OutputInterface $output) { $this->setupFormatters($output->getFormatter()); $finder = new Finder(); $phpcs = new CodeSniffer(0); $phpcsCli = new CLI(); $phpcsCli->errorSeverity = PHPCS_DEFAULT_ERROR_SEV; $phpcsCli->warningSeverity = PHPCS_DEFAULT_WARN_SEV; $phpcsCli->dieOnUnknownArg = false; $phpcsCli->setCommandLineValues(['--colors', '-p', '--report=full']); $phpcs->setCli($phpcsCli); $existing = []; foreach (RootDirectories::getEnforceable() as $directory) { if (file_exists($directory) && is_dir($directory)) { $existing[] = $directory; } } $files = $finder->files()->in($existing)->notName('*Sniff.php')->ignoreUnreadableDirs()->ignoreDotFiles(true)->ignoreVCS(true)->name('*.php'); $phpcs->reporting->startTiming(); $phpcs->initStandard(Anchor::getDirectory()); $files = array_keys(iterator_to_array($files->getIterator())); $processed = []; $withErrors = []; $withWarnings = []; foreach ($files as $file) { $done = $phpcs->processFile($file); if ($done->getErrorCount() > 0) { $output->write('E'); $withErrors[] = $done; if ($done->getWarningCount() > 0) { $withWarnings[] = $done; } } elseif ($done->getWarningCount() > 0) { $output->write('W'); $withWarnings[] = $done; } else { $output->write('.'); } $processed[] = $done; } $this->renderSummary($withErrors, $withWarnings, $output); }
/** * 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. * @param array $restrictions The sniff codes to restrict the * violations to. * * @return PHP_CodeSniffer_File * @throws PHP_CodeSniffer_Exception If the file could not be processed. * @see _processFile() */ public function processFile($file, $contents = null, $restrictions = array()) { 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; } } } //end if try { $phpcsFile = $this->_processFile($file, $contents, $restrictions); } 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->_tokenListeners, $this->allowedFileExtensions, $this->ruleset, $restrictions, $this); $phpcsFile->addError($error, null); } //end try $cliValues = $this->cli->getCommandLineValues(); if (PHP_CODESNIFFER_INTERACTIVE === false) { // Cache the report data for this file so we can unset it to save memory. $this->reporting->cacheFileReport($phpcsFile, $cliValues); return $phpcsFile; } /* Running interactively. Print the error report for the current file and then wait for user input. */ // 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) { $numErrors = $phpcsFile->getErrorCount() + $phpcsFile->getWarningCount(); if ($numErrors === 0) { continue; } $reportClass = $this->reporting->factory('full'); $reportData = $this->reporting->prepareFileReport($phpcsFile); $reportClass->generateFileReport($reportData, $cliValues['showSources'], $cliValues['reportWidth']); echo '<ENTER> to recheck, [s] to skip or [q] to quit : '; $input = fgets(STDIN); $input = trim($input); switch ($input) { case 's': break 2; 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, $restrictions); break; } } //end while return $phpcsFile; }
<?php php_sapi_name() == 'cli' ?: die('CLI only'); // Script defines define('REPO_BASE', dirname(__DIR__)); // Require Composer autoloader if (!file_exists(REPO_BASE . '/vendor/autoload.php')) { fwrite(STDOUT, "[37;41mThis script requires Composer to be set up, please run 'composer install' first.[0m\n"); } require REPO_BASE . '/vendor/autoload.php'; // Welcome message fwrite(STDOUT, "[32;1mInitializing PHP_CodeSniffer checks.[0m\n"); // Ignored files $ignored = array(REPO_BASE . '/component/admin/views/*/tmpl/*', REPO_BASE . '/component/admin/layouts/*', REPO_BASE . '/component/site/views/*/tmpl/*', REPO_BASE . '/component/site/layouts/*'); // Build the options for the sniffer $options = array('files' => array(REPO_BASE . '/plugins', REPO_BASE . '/components', REPO_BASE . '/libraries'), 'standard' => array(REPO_BASE . '/.travis/phpcs/Joomla'), 'ignored' => $ignored, 'showProgress' => true, 'verbosity' => false); // Instantiate the sniffer $phpcs = new PHP_CodeSniffer_CLI(); // Ensure PHPCS can run, will exit if requirements aren't met $phpcs->checkRequirements(); // Run the sniffs $numErrors = $phpcs->process($options); // If there were errors, output the number and exit the app with a fail code if ($numErrors) { fwrite(STDOUT, sprintf("[37;41mThere were %d issues detected.[0m\n", $numErrors)); exit(1); } else { fwrite(STDOUT, "[32;1mThere were no issues detected.[0m\n"); exit(0); }
<?php /** * Pre-commit hook entry point * * PHP version 5 * * @category DiffSniffer * @package DiffSniffer * @author Sergei Morozov <*****@*****.**> * @copyright 2014 Sergei Morozov * @license http://mit-license.org/ MIT Licence * @link http://github.com/morozov/diff-sniffer-pre-commit */ $autoload = __DIR__ . '/../vendor/autoload.php'; if (!file_exists($autoload)) { echo 'You must set up the project dependencies, run the following commands:' . PHP_EOL . 'curl -sS https://getcomposer.org/installer | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL; exit(2); } require $autoload; $arguments = $_SERVER['argv']; array_shift($arguments); if ($arguments && $arguments[0] == '--version') { echo 'Diff Sniffer Pre-Commit Hook version 2.3.0.1' . PHP_EOL; $cli = new PHP_CodeSniffer_CLI(); $cli->processLongArgument('version', null, null); exit; } $runner = new \DiffSniffer\Runner\Staged(); $return_var = $runner->run(getcwd(), $arguments); exit($return_var);
private function parseOtherOpts($params) { foreach ($params as $key => $value) { switch ($key) { case "a": case "aggressive": $this->scisr->setEditMode(ScisrRunner::MODE_AGGRESSIVE); break; case "no-inheritance": $this->withInheritance = false; break; case "t": case "timid": $this->scisr->setEditMode(ScisrRunner::MODE_TIMID); break; case "i": case "ignore": // We doctor and pass this value in to let phpcs run a pattern on it $fakekey = 'ignore=' . $value; $cli = new PHP_CodeSniffer_CLI(); $result = $cli->processLongArgument($fakekey, null, array()); $this->scisr->setIgnorePatterns($result['ignored']); break; case "e": case "extensions": // We doctor and pass this value in to let phpcs run a pattern on it $fakekey = 'extensions=' . $value; $cli = new PHP_CodeSniffer_CLI(); $result = $cli->processLongArgument($fakekey, null, array()); $this->scisr->setAllowedFileExtensions($result['extensions']); break; case "help": $this->showHelp = true; break; } } }
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsArguments = ['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php'], 'warningSeverity' => 0]; $phpcsViolations = $phpcsCLI->process($phpcsArguments); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration]; $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $cloverCoverage = new PHP_CodeCoverage_Report_Clover(); file_put_contents('clover.xml', $cloverCoverage->process($result->getCodeCoverage())); $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
* http://phpmd.org * * This script looks for various mess analysis (codesize, design, naming, * unused) - by default we execute all reporting them in PMD format * so can be processed later by some PMD tools. Useful to build some CI jobs * on top of it. * * @package core * @subpackage ci * @copyright 2011 Eloy Lafuente (http://stronk7.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ // Increase memory, codebase is huge ini_set('memory_limit', '4352M'); // Verify local_codechecker is installed and use // it if available. Else, try default execution that // will lead to use the one installed via pear. $localcspath = __DIR__ . '/../../codechecker/pear'; if (file_exists($localcspath)) { set_include_path($localcspath . PATH_SEPARATOR . get_include_path()); } error_reporting(E_ALL | E_STRICT); include_once 'PHP/CodeSniffer/CLI.php'; $phpcs = new PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); $numerrors = $phpcs->process(); if ($numerrors === 0) { exit(0); } else { exit(1); }
/** * @codeCoverageIgnore hard coded `exit()` in `parent::runphpcs` */ public function runphpcs() { $this->processConfig(); parent::runphpcs(); }
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['bin', 'src', 'tests', 'build.php']]); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration]; $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments, false); if (!$result->wasSuccessful()) { exit(1); } $coverageReport = $result->getCodeCoverage()->getReport(); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
/** * CodeSnifferShell::_process() * * @return int Exit */ protected function _process() { include_once 'PHP/CodeSniffer/CLI.php'; $phpcs = new PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); $cliValues = $phpcs->getCommandLineValues(); if ($this->params['fix']) { // Override some of the command line settings that might be used and stop us // gettting a diff file. $diffFile = TMP . 'phpcbf-fixed.diff'; $cliValues['generator'] = ''; $cliValues['explain'] = false; $cliValues['reports'] = ['diff' => $diffFile]; if (file_exists($diffFile) === true) { unlink($diffFile); } } $numErrors = $phpcs->process($cliValues); $exit = 0; if ($this->params['fix']) { if (file_exists($diffFile) === false) { // Nothing to fix. if ($numErrors === 0) { // And no errors reported. $exit = 0; } else { // Errors we can't fix. $exit = 2; } } else { $cmd = "cd / && patch -p0 -ui \"{$diffFile}\" && cd \"" . APP . "\""; $output = []; $retVal = null; exec($cmd, $output, $retVal); unlink($diffFile); if ($retVal === 0) { // Everything went well. $filesPatched = count($output); echo "Patched {$filesPatched} files\n"; $exit = 1; } else { print_r($output); echo "Returned: {$retVal}\n"; $exit = 3; } } } if ($numErrors !== 0) { $this->err('An error occured during processing.'); } return $exit; }
/** * 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) { if (substr($arg, 0, 6) === 'level=') { $showLevel = strtoupper(substr($arg, 6)); if (defined('SQLI_CodeSniffer_Reports::' . $showLevel)) { $values['showLevel'] = constant('SQLI_CodeSniffer_Reports::' . $showLevel); } } elseif ($arg == 'version') { echo 'SQLI_CodeSniffer version @package_version@ (alpha) '; echo 'by SQLI (http://www.sqli.com)' . PHP_EOL; exit(0); } else { $values = parent::processLongArgument($arg, $pos, $values); } return $values; }
<?php // Bootstrap the application. require __DIR__ . '/../src/bootstrap.php'; error_reporting(E_ALL | E_STRICT); // Set up the command line interface. $phpcs = new PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); // Add the Drupal standard. $values = $phpcs->getCommandLineValues(); $standard = dirname(__DIR__) . '/src/Drupal'; if (!isset($values['standard'])) { $values['standard'] = $standard; } else { $values['standard'] .= ',' . $standard; } // Process width PHP CodeSnifer. $numErrors = $phpcs->process($values); if ($numErrors === 0) { exit(0); } else { exit(1); }
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'))); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
$values['tabWidth'] = 4; $values['encoding'] = 'utf-8'; $values['standard'] = 'PEAR'; $values['generator'] = ''; //END OF USER CONFIGURABLE OPTIONS/// $path = 'PHP/CodeSniffer/CLI.php'; if (!file_exists($path)) { echo 'File not found: ' . $path . '. Pear must be in your path. If not you need to set the correct path to Pear\'s CodeSniffer. ' . 'Included paths: ' . get_include_path() . '. Change it in this file: ' . __FILE__; die; } $file = getenv('CODA_FILEPATH'); $files = array($file); $values['files'] = $files; $values['reportFile'] = '/tmp/checkstyle.txt'; $values['interactive'] = false; $values['sniffs'] = array(); $values['extensions'] = array(); $values['ignored'] = array(); $values['reports'] = array(); $values['errorSeverity'] = ''; $values['warningSeverity'] = ''; $values['local'] = ''; $values['reportWidth'] = ''; $values['showProgress'] = ''; $values['showSources'] = ''; require $path; $phpcs = new PHP_CodeSniffer_CLI(); $phpcs->checkRequirements(); $numErrors = $phpcs->process($values); echo file_get_contents($values['reportFile']);
/** * Process the sniffs for a single file. * * Does raw processing only. No interactive support or error checking. * * @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 * @see processFile() */ private function _processFile($file, $contents) { $stdin = false; $cliValues = $this->cli->getCommandLineValues(); if (empty($cliValues['files']) === true) { $stdin = true; } if (PHP_CODESNIFFER_VERBOSITY > 0 || PHP_CODESNIFFER_CBF === true && $stdin === false) { $startTime = microtime(true); echo 'Processing ' . basename($file) . ' '; if (PHP_CODESNIFFER_VERBOSITY > 1) { echo PHP_EOL; } } $phpcsFile = new PHP_CodeSniffer_File($file, $this->_tokenListeners, $this->ruleset, $this); $phpcsFile->start($contents); if (PHP_CODESNIFFER_VERBOSITY > 0 || PHP_CODESNIFFER_CBF === true && $stdin === false) { $timeTaken = (microtime(true) - $startTime) * 1000; if ($timeTaken < 1000) { $timeTaken = round($timeTaken); echo "DONE in {$timeTaken}ms"; } else { $timeTaken = round($timeTaken / 1000, 2); echo "DONE in {$timeTaken} secs"; } if (PHP_CODESNIFFER_CBF === true) { $errors = $phpcsFile->getFixableCount(); echo " ({$errors} fixable violations)" . PHP_EOL; } else { $errors = $phpcsFile->getErrorCount(); $warnings = $phpcsFile->getWarningCount(); echo " ({$errors} errors, {$warnings} warnings)" . PHP_EOL; } } return $phpcsFile; }
/** * Get a list of default values for all possible command line arguments. * * @return array */ public function getDefaults() { $defaults = parent::getDefaults(); $defaults['standard'] = array('Drupal'); // The Sniffer tries really hard to discard its logs // ALL the time unless we tell it not to. // All these settings are just to prevent that amnesia. $defaults['showSources'] = TRUE; $defaults['verbosity'] = 1; $defaults['reports'] = array('full' => NULL); $defaults['warningSeverity'] = PHPCS_DEFAULT_WARN_SEV; // If the severities are left as the default (zero) then // NOTHING is considered worth logging or even counting! $this->warningSeverity = PHPCS_DEFAULT_WARN_SEV; $this->errorSeverity = PHPCS_DEFAULT_ERROR_SEV; return $defaults; }