Initialise the standard that the run will use.
public initStandard ( string | array $standards, array $restrictions = [], array $exclusions = [] ) : void | ||
$standards | string | array | The set of code sniffs we are testing against. |
$restrictions | array | The sniff codes to restrict the testing to. |
$exclusions | array | The sniff codes to exclude from testing. |
return | void |
/** * Tests the extending classes Sniff class. */ public final function testSniff() { // Skip this test if we can't run in this environment. if ($this->shouldSkipTest() === true) { $this->markTestSkipped(); } $testFiles = $this->getTestFiles(); $sniffCodes = $this->getSniffCodes(); self::$phpcs->initStandard(dirname(__DIR__) . '/src/Drupal', $sniffCodes); $failureMessages = array(); foreach ($testFiles as $testFile) { try { $phpcsFile = self::$phpcs->processFile($testFile); } catch (Exception $e) { $this->fail('An unexpected exception has been caught: ' . $e->getMessage()); } $failures = $this->generateFailureMessages($phpcsFile); $failureMessages = array_merge($failureMessages, $failures); if ($phpcsFile->getFixableCount() > 0) { // Attempt to fix the errors. $phpcsFile->fixer->fixFile(); $fixable = $phpcsFile->getFixableCount(); if ($fixable > 0) { $filename = basename($testFile); $failureMessages[] = "Failed to fix {$fixable} fixable violations in {$filename}"; } } } //end foreach() if (empty($failureMessages) === false) { $this->fail(implode(PHP_EOL, $failureMessages)); } }
/** * @param Logger $log * @param array $phpcs - ['encoding' => '....', 'standard' => '...'] */ public function __construct(Logger $log, array $config) { $this->log = $log; if (!empty($config['installed_paths'])) { $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'] = array('installed_paths' => str_replace('%root%', dirname(__DIR__), $config['installed_paths'])); $this->log->debug("installed_paths=" . $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA']['installed_paths']); } $this->phpcs = new \PHP_CodeSniffer($verbosity = 0, $tabWidth = 0, $config['encoding'], $interactive = false); $this->log->debug("PhpCs config", $config); $this->phpcs->cli->setCommandLineValues(['--report=json', '--standard=' . $config['standard']]); $this->phpcs->initStandard($config['standard']); }
/** * Tests the extending classes Sniff class. * * @return void * @throws PHPUnit_Framework_Error */ public final function testSniff() { // Skip this test if we can't run in this environment. if ($this->shouldSkipTest() === true) { $this->markTestSkipped(); } $testFiles = $this->getTestFiles(); $sniffCodes = $this->getSniffCodes(); // Determine the standard to be used from the class name. $class_name_parts = explode('_', get_class($this)); $standard = $class_name_parts[0]; $failureMessages = array(); foreach ($testFiles as $testFile) { self::$phpcs->initStandard("coder_sniffer/{$standard}", $sniffCodes); $filename = basename($testFile); try { $cliValues = $this->getCliValues($filename); self::$phpcs->cli->setCommandLineValues($cliValues); $phpcsFile = self::$phpcs->processFile($testFile); } catch (Exception $e) { $this->fail('An unexpected exception has been caught: ' . $e->getMessage()); } $failures = $this->generateFailureMessages($phpcsFile); $failureMessages = array_merge($failureMessages, $failures); // Attempt to fix the errors. // Re-initialize the standard to use all sniffs for the fixer. self::$phpcs->initStandard("coder_sniffer/{$standard}"); self::$phpcs->cli->setCommandLineValues($cliValues); $phpcsFile = self::$phpcs->processFile($testFile); $phpcsFile->fixer->fixFile(); $fixable = $phpcsFile->getFixableCount(); if ($fixable > 0) { $failureMessages[] = "Failed to fix {$fixable} fixable violations in {$filename}"; } // Check for a .fixed file to check for accuracy of fixes. $fixedFile = $testFile . '.fixed'; if (file_exists($fixedFile) === true) { $diff = $phpcsFile->fixer->generateDiff($fixedFile); if (trim($diff) !== '') { $filename = basename($testFile); $fixedFilename = basename($fixedFile); $failureMessages[] = "Fixed version of {$filename} does not match expected version in {$fixedFilename}; the diff is\n{$diff}"; } } } //end foreach if (empty($failureMessages) === false) { $this->fail(implode(PHP_EOL, $failureMessages)); } }
/** * Tests the extending classes Sniff class. * * @return void * @throws PHPUnit_Framework_Error */ public final function testSniff() { // Skip this test if we can't run in this environment. if ($this->shouldSkipTest() === true) { $this->markTestSkipped(); } self::$phpcs->initStandard(self::$standardName, [self::$sniffCode]); self::$phpcs->setIgnorePatterns([]); $failureMessages = []; foreach (self::$testFiles as $testFile) { $filename = basename($testFile); try { $cliValues = $this->getCliValues($filename); self::$phpcs->cli->setCommandLineValues($cliValues); $phpcsFile = self::$phpcs->processFile($testFile); } catch (Exception $e) { $this->fail('An unexpected exception has been caught: ' . $e->getMessage()); } $failures = $this->generateFailureMessages($phpcsFile); $failureMessages = array_merge($failureMessages, $failures); } if (empty($failureMessages) === false) { $this->fail(implode(PHP_EOL, $failureMessages)); } }
/** * @param $file string * * @return int ErrorCount */ protected function sniffFile($file) { $phpCs = new \PHP_CodeSniffer(); $phpCs->initStandard(realpath(__DIR__ . '/../Standards/Symfony2')); $result = $phpCs->processFile($file); $errors = $result->getErrorCount(); return $errors; }
/** * Runs PHP sniff analysis. * * @return []string * Textual summary of the analysis. */ function getSniffAnalysis(Module $module, $extensions) { #print_r(get_defined_vars()); $verbosity = 1; // Run php analyser directly as PHP. $phpcs = new \PHP_CodeSniffer($verbosity); // Need to emulate a CLI environment in order to pass certain settings down // to the internals. // Decoupling here is atrocious. $cli = new SniffReporter(); $phpcs->setCli($cli); // Parameters passed to phpcs. // Normally we just name the standard, // but passing the full path to it also works. $values = array('standard' => 'Drupal', 'sniffs' => array()); try { $phpcs->initStandard($values['standard'], $values['sniffs']); } catch (Exception $e) { $message = "Could not initialize coding standard " . $values['standard'] . " " . $e->getMessage(); error_log($message); return array($message); } $analysis = array(); try { // PHPCS handles recursion on its own. // $analysis = $phpcs->processFiles($module->getLocation()); // But we have already enumerated the files, so lets keep consistent. $tree = $module->getCodeFiles($extensions); // $analysis = $phpcs->processFiles($tree); // processFiles is too abstract, it doesn't return the individual results. // Do the iteration ourselves. foreach ($tree as $filepath) { /** @var PHP_CodeSniffer_File $analysed */ $analysed = $phpcs->processFile($filepath); $analysis[$filepath] = $analysed; } } catch (Exception $e) { $message = "When processing " . $module->getLocation() . " " . $e->getMessage(); error_log($message); } // Params for reporting. $report = 'full'; $showSources = FALSE; $cliValues = array('colors' => FALSE); $reportFile = 'report.out'; $result = $phpcs->reporting->printReport($report, $showSources, $cliValues, $reportFile); #print_r($result); return $analysis; }
/** * 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); }
/** * Runs PHP_CodeSniffer over files and directories. * * @param array $values An array of values determined from CLI args. * * @return int The number of error and warning messages shown. * @see getCommandLineValues() */ public function process($values = array()) { if (empty($values) === true) { $values = $this->getCommandLineValues(); } else { $values = array_merge($this->getDefaults(), $values); $this->values = $values; } if ($values['generator'] !== '') { $phpcs = new PHP_CodeSniffer($values['verbosity']); if ($values['standard'] === null) { $values['standard'] = $this->validateStandard(null); } foreach ($values['standard'] as $standard) { $phpcs->generateDocs($standard, $values['sniffs'], $values['generator']); } exit(0); } // If no standard is supplied, get the default. $values['standard'] = $this->validateStandard($values['standard']); foreach ($values['standard'] as $standard) { if (PHP_CodeSniffer::isInstalledStandard($standard) === false) { // They didn't select a valid coding standard, so help them // out by letting them know which standards are installed. echo 'ERROR: the "' . $standard . '" coding standard is not installed. '; $this->printInstalledStandards(); exit(2); } } if ($values['explain'] === true) { foreach ($values['standard'] as $standard) { $this->explainStandard($standard); } exit(0); } $phpcs = new PHP_CodeSniffer($values['verbosity'], null, null, null); $phpcs->setCli($this); $phpcs->initStandard($values['standard'], $values['sniffs']); $values = $this->values; $phpcs->setTabWidth($values['tabWidth']); $phpcs->setEncoding($values['encoding']); $phpcs->setInteractive($values['interactive']); // Set file extensions if they were specified. Otherwise, // let PHP_CodeSniffer decide on the defaults. if (empty($values['extensions']) === false) { $phpcs->setAllowedFileExtensions($values['extensions']); } // Set ignore patterns if they were specified. if (empty($values['ignored']) === false) { $ignorePatterns = array_merge($phpcs->getIgnorePatterns(), $values['ignored']); $phpcs->setIgnorePatterns($ignorePatterns); } // Set some convenience member vars. if ($values['errorSeverity'] === null) { $this->errorSeverity = PHPCS_DEFAULT_ERROR_SEV; } else { $this->errorSeverity = $values['errorSeverity']; } if ($values['warningSeverity'] === null) { $this->warningSeverity = PHPCS_DEFAULT_WARN_SEV; } else { $this->warningSeverity = $values['warningSeverity']; } if (empty($values['reports']) === true) { $values['reports']['full'] = $values['reportFile']; $this->values['reports'] = $values['reports']; } // Include bootstrap files. foreach ($values['bootstrap'] as $bootstrap) { include $bootstrap; } $phpcs->processFiles($values['files'], $values['local']); if (empty($values['files']) === true || $values['stdin'] !== null) { $fileContents = $values['stdin']; if ($fileContents === null) { // Check if they are passing in the file contents. $handle = fopen('php://stdin', 'r'); stream_set_blocking($handle, true); $fileContents = stream_get_contents($handle); fclose($handle); } if ($fileContents === '') { // No files and no content passed in. echo 'ERROR: You must supply at least one file or directory to process.' . PHP_EOL . PHP_EOL; $this->printUsage(); exit(2); } else { $phpcs->processFile('STDIN', $fileContents); } } // Interactive runs don't require a final report and it doesn't really // matter what the retun value is because we know it isn't being read // by a script. if ($values['interactive'] === true) { return 0; } return $this->printErrorReport($phpcs, $values['reports'], $values['showSources'], $values['reportFile'], $values['reportWidth']); }
/** * Test suppressing a whole file. * * @return void */ public function testSuppressFile() { $phpcs = new PHP_CodeSniffer(); $phpcs->initStandard('Generic', array('Generic.Commenting.Todo')); // Process without suppression. $content = '<?php ' . PHP_EOL . '//TODO: write some code'; $file = $phpcs->processFile('suppressionTest.php', $content); $warnings = $file->getWarnings(); $numWarnings = $file->getWarningCount(); $this->assertEquals(1, $numWarnings); $this->assertEquals(1, count($warnings)); // Process with suppression. $content = '<?php ' . PHP_EOL . '// @codingStandardsIgnoreFile' . PHP_EOL . '//TODO: write some code'; $file = $phpcs->processFile('suppressionTest.php', $content); $warnings = $file->getWarnings(); $numWarnings = $file->getWarningCount(); $this->assertEquals(0, $numWarnings); $this->assertEquals(0, count($warnings)); // Process with a Doc Block suppression. $content = '<?php ' . PHP_EOL . '/* @codingStandardsIgnoreFile */' . PHP_EOL . '//TODO: write some code'; $file = $phpcs->processFile('suppressionTest.php', $content); $warnings = $file->getWarnings(); $numWarnings = $file->getWarningCount(); $this->assertEquals(0, $numWarnings); $this->assertEquals(0, count($warnings)); }
/** * Tests the extending classes Sniff class. * * @return void * @throws PHPUnit_Framework_Error */ public final function testSniff() { // Skip this test if we can't run in this environment. if ($this->shouldSkipTest() === true) { $this->markTestSkipped(); } // The basis for determining file locations. $basename = substr(get_class($this), 0, -8); // The name of the coding standard we are testing. $standardName = substr($basename, 0, strpos($basename, '_')); // The code of the sniff we are testing. $parts = explode('_', $basename); $sniffCode = $parts[0] . '.' . $parts[2] . '.' . $parts[3]; $testFileBase = $this->standardsDir . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $basename) . 'UnitTest.'; // Get a list of all test files to check. These will have the same base // name but different extensions. We ignore the .php file as it is the class. $testFiles = array(); $dir = substr($testFileBase, 0, strrpos($testFileBase, DIRECTORY_SEPARATOR)); $di = new DirectoryIterator($dir); foreach ($di as $file) { $path = $file->getPathname(); if (substr($path, 0, strlen($testFileBase)) === $testFileBase) { if ($path !== $testFileBase . 'php' && substr($path, -5) !== 'fixed') { $testFiles[] = $path; } } } // Get them in order. sort($testFiles); self::$phpcs->initStandard($standardName, array($sniffCode)); self::$phpcs->setIgnorePatterns(array()); $failureMessages = array(); foreach ($testFiles as $testFile) { $filename = basename($testFile); try { $cliValues = $this->getCliValues($filename); self::$phpcs->cli->setCommandLineValues($cliValues); $phpcsFile = self::$phpcs->processFile($testFile); } catch (Exception $e) { $this->fail('An unexpected exception has been caught: ' . $e->getMessage()); } $failures = $this->generateFailureMessages($phpcsFile); $failureMessages = array_merge($failureMessages, $failures); if ($phpcsFile->getFixableCount() > 0) { // Attempt to fix the errors. $phpcsFile->fixer->fixFile(); $fixable = $phpcsFile->getFixableCount(); if ($fixable > 0) { $failureMessages[] = "Failed to fix {$fixable} fixable violations in {$filename}"; } // Check for a .fixed file to check for accuracy of fixes. $fixedFile = $testFile . '.fixed'; if (file_exists($fixedFile) === true) { $diff = $phpcsFile->fixer->generateDiff($fixedFile); if (trim($diff) !== '') { $filename = basename($testFile); $fixedFilename = basename($fixedFile); $failureMessages[] = "Fixed version of {$filename} does not match expected version in {$fixedFilename}; the diff is\n{$diff}"; } } } } //end foreach if (empty($failureMessages) === false) { $this->fail(implode(PHP_EOL, $failureMessages)); } }
private function checkCodingStandard() { require_once __DIR__ . '/vendor/PHP_CodeSniffer-2.2.0/CodeSniffer.php'; $phpcs = new \PHP_CodeSniffer(); $arguments = array('--standard=CodeIgniter', '-s'); $_SERVER['argv'] = isset($_SERVER['argv']) ? $_SERVER['argv'] + $arguments : $arguments; $phpcs->initStandard('CodeIgniter'); $phpcs->setAllowedFileExtensions(array('PHP')); $folders = array('controllers', 'libraries', 'models', 'helpers'); $loadedFiles = array_merge(array($this->ci->router->class), array_keys($this->loadLibraries()), $this->ci->load->get_models(), array_keys($this->ci->load->get_helpers())); array_walk($loadedFiles, function (&$item) { $item = strtolower($item) . '.php'; }); $reports = array(); foreach ($folders as $folder) { $path = APPPATH . $folder . '/'; $directoryIterator = new \RecursiveDirectoryIterator($path); foreach ($directoryIterator as $fileInfo) { if ($fileInfo->isFile() && in_array(strtolower($fileInfo->getFileName()), $loadedFiles)) { $phpcsFile = $phpcs->processFile($fileInfo->getPathName()); $reportData = $phpcs->reporting->prepareFileReport($phpcsFile); if (count($reportData['messages'])) { foreach ($reportData['messages'] as $line => $_messages) { foreach ($_messages as $message) { foreach ($message as $msg) { $reports[] = array('filename' => str_replace(str_replace('\\', '/', FCPATH), '', str_replace('\\', '/', $reportData['filename'])), 'filepath' => $reportData['filename'], 'severity' => $msg['type'], 'line' => $line, 'message' => $msg['message']); } } } } } } } return $reports; }
/** * {@inheritdoc} */ public function initStandard($standards, array $restrictions = array(), array $exclusions = array()) { $this->tokenListeners = array(); parent::initStandard($standards, $restrictions); }
public function testPlugins() { $plugin_path = dirname(__FILE__) . '/../../fannie/modules/plugins2.0/'; $first = array('CwReportDataSource' => ''); $files = array(); foreach (FannieAPI::listFiles($plugin_path) as $file) { $class = substr(basename($file), 0, strlen(basename($file)) - 4); if (isset($first[$class])) { $first[$class] = $file; } else { $files[] = $file; } } foreach ($first as $class => $file) { array_unshift($files, $file); } $functions = get_defined_functions(); $sniffer = null; $standard = dirname(__FILE__) . '/CodingStandard/CORE_PSR1/'; if (getenv('TRAVIS') === false && class_exists('PHP_CodeSniffer')) { $sniffer = new PHP_CodeSniffer(); $sniffer->initStandard($standard); $sniffer->cli->setCommandLineValues(array('--report=Json')); $sniffer->cli->setCommandLineValues($files); $sniffer->processFiles($files); ob_start(); $sniffer->reporting->printReport('Json', true, $sniffer->cli->getCommandLineValues(), null); $json = ob_get_clean(); $json = json_decode($json, true); $errors = 0; $errorMsg = ''; $json = $json['files']; foreach ($json as $filename => $jsonfile) { foreach ($jsonfile['messages'] as $message) { if ($message['type'] == 'ERROR') { $errors++; $errorMsg .= $filename . ': ' . $message['message'] . "\n"; } else { echo "Coding Standard Warning: " . $filename . ': ' . $message['message'] . "\n"; } } } $this->assertEquals(0, $errors, $errorMsg); } else { echo "PHP_CodeSniffer is not installed. This test will be less effective.\n"; echo "Use composer to install it.\n"; } foreach ($files as $file) { $file = realpath($file); $class_name = substr(basename($file), 0, strlen(basename($file)) - 4); $namespaced_class_name = FannieAPI::pathToClass($file); if (class_exists($class_name, false)) { // may have already been included $reflect = new ReflectionClass($class_name); $this->assertEquals($file, $reflect->getFileName(), $class_name . ' is defined by ' . $file . ' AND ' . $reflect->getFileName()); } elseif (class_exists($namespaced_class_name, false)) { // may have already been included $reflect = new ReflectionClass($namespaced_class_name); $this->assertEquals($file, $reflect->getFileName(), $namespaced_class_name . ' is defined by ' . $file . ' AND ' . $reflect->getFileName()); } else { ob_start(); include $file; $output = ob_get_clean(); $this->assertEquals('', $output, $file . ' produces output when included'); $current_functions = get_defined_functions(); $this->assertEquals(count($functions['user']), count($current_functions['user']), $file . ' has defined additional functions: ' . $this->detailedFunctionDiff($current_functions['user'], $functions['user'])); $classes = get_declared_classes(); $this->assertThat($classes, $this->logicalOr($this->contains($class_name), $this->contains($namespaced_class_name), $this->contains(ltrim($namespaced_class_name, '\\'))), $file . ' does not define ' . $class_name . ' or ' . $namespaced_class_name); } } }