setIgnorePatterns() public method

Patterns are not case sensitive.
public setIgnorePatterns ( array $patterns ) : void
$patterns array An array of ignore patterns. The pattern is the key and the value is either "absolute" or "relative", depending on how the pattern should be applied to a file path.
return void
 /**
  * Sets up this unit test.
  *
  * @return void
  */
 protected function setUp()
 {
     if (self::$phpcs === null) {
         self::$phpcs = new PHP_CodeSniffer();
     }
     PHP_CodeSniffer::setConfigData('testVersion', null, true);
     self::$phpcs->process(array(), 'PHPCompatibility');
     self::$phpcs->setIgnorePatterns(array());
 }
 /**
  * Sets up this unit test.
  *
  * @return void
  */
 protected function setUp()
 {
     if (self::$phpcs === null) {
         self::$phpcs = new PHP_CodeSniffer();
     }
     PHP_CodeSniffer::setConfigData('testVersion', null, true);
     if (method_exists('PHP_CodeSniffer_CLI', 'setCommandLineValues')) {
         // For PHPCS 2.x
         self::$phpcs->cli->setCommandLineValues(array('-p', '--colors'));
     }
     self::$phpcs->process(array(), __DIR__ . '/../');
     self::$phpcs->setIgnorePatterns(array());
 }
 /**
  * Tests the extending classes Sniff class.
  *
  * @return void
  * @throws PHPUnit_Framework_Error
  */
 protected final function runTest()
 {
     // 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 class name of the sniff we are testing.
     $sniffClass = str_replace('_Tests_', '_Sniffs_', $basename) . 'Sniff';
     if (is_file(dirname(__FILE__) . '/../../CodeSniffer.php') === true) {
         // We have not been installed.
         $standardsDir = realpath(dirname(__FILE__) . '/../../CodeSniffer/Standards');
         $testFileBase = $standardsDir . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $basename) . 'UnitTest.';
     } else {
         // The name of the dummy file we are testing.
         $testFileBase = dirname(__FILE__) . 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') {
                 $testFiles[] = $path;
             }
         }
     }
     // Get them in order.
     sort($testFiles);
     self::$phpcs->process(array(), $standardName, array($sniffClass));
     self::$phpcs->setIgnorePatterns(array());
     $failureMessages = array();
     foreach ($testFiles as $testFile) {
         try {
             self::$phpcs->processFile($testFile);
         } catch (Exception $e) {
             $this->fail('An unexpected exception has been caught: ' . $e->getMessage());
         }
         $files = self::$phpcs->getFiles();
         if (empty($files) === true) {
             // File was skipped for some reason.
             echo "Skipped: {$testFile}\n";
             $this->markTestSkipped();
         }
         $file = array_pop($files);
         $failures = $this->generateFailureMessages($file);
         $failureMessages = array_merge($failureMessages, $failures);
     }
     //end foreach
     if (empty($failureMessages) === false) {
         $this->fail(implode(PHP_EOL, $failureMessages));
     }
 }
 /**
  * Tests the extending classes Sniff class.
  *
  * @test
  * @return void
  * @throws PHPUnit_Framework_Error
  */
 public final function runTest()
 {
     // Skip this test if we can't run in this environment.
     if ($this->shouldSkipTest() === true) {
         $this->markTestSkipped();
     }
     if (!defined('TEST_PATH') || realpath(TEST_PATH) === false) {
         throw new \Exception('TEST_PATH is not defined');
     }
     $testClassFile = (new ReflectionClass(get_class($this)))->getFileName();
     $testClassFile = realpath($testClassFile);
     $testFile = dirname($testClassFile) . '/' . basename($testClassFile, '.php') . '.inc';
     if (!is_file($testFile)) {
         $this->fail("Required file [{$testFile}] not found");
     }
     self::$phpcs->process(array(), $this->getStandardName(), array($this->getSniffCode()));
     self::$phpcs->setIgnorePatterns(array());
     try {
         $phpcsFile = self::$phpcs->processFile($testFile);
     } catch (Exception $e) {
         $this->fail('An unexpected exception has been caught: ' . $e->getMessage());
     }
     $failureMessages = $this->generateFailureMessages($phpcsFile);
     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));
     }
 }
 /**
  * Create PHP_CodeSniffer instance
  *
  * @param array $restrictions Restrictions
  *
  * @return \PHP_CodeSniffer
  */
 protected function getCodeSniffer(array $restrictions)
 {
     $codeSniffer = new \PHP_CodeSniffer();
     $codeSniffer->cli->setCommandLineValues(array("--report=summary"));
     $infoReporting = $codeSniffer->reporting->factory("summary");
     /** @var \PHP_CodeSniffer_Reports_Info $infoReporting */
     $infoReporting->recordErrors = true;
     $codeSniffer->process(array(), __DIR__ . "/..", $restrictions);
     $codeSniffer->setIgnorePatterns(array());
     return $codeSniffer;
 }
 /**
  * Tests the extending classes Sniff class.
  *
  * @return void
  * @throws PHPUnit_Framework_Error
  * @test
  */
 public final function runTest()
 {
     self::$_phpcs->process([], 'DWS', [$this->_getSniffName()]);
     self::$_phpcs->setIgnorePatterns([]);
     $testFile = dirname(__DIR__) . '/tests/' . str_replace('_', '/', get_class($this)) . '.inc';
     if (!file_exists($testFile)) {
         $this->markTestSkipped();
         return;
     }
     try {
         self::$_phpcs->processFile($testFile);
     } catch (Exception $e) {
         $this->fail("An unexpected exception has been caught: {$e->getMessage()}");
     }
     $files = self::$_phpcs->getFiles();
     if ($files === []) {
         echo "Skipped: {$testFile}\n";
         $this->markTestSkipped();
     }
     $failureMessages = $this->generateFailureMessages($files[0]);
     if (count($failureMessages) > 0) {
         $this->fail(implode("\n", $failureMessages));
     }
 }
 /**
  * Tests the extending classes Sniff class.
  *
  * @return void
  */
 protected final function runTest()
 {
     // 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];
     // The name of the dummy file we are testing.
     $testFileBase = dirname(__DIR__) . 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));
     $iterator = new DirectoryIterator($dir);
     foreach ($iterator as $file) {
         $path = $file->getPathname();
         if (substr($path, 0, strlen($testFileBase)) === $testFileBase) {
             if ($path !== $testFileBase . 'php') {
                 $testFiles[] = $path;
             }
         }
     }
     // Get them in order.
     sort($testFiles);
     self::$phpcs->process(array(), $standardName . '/ruleset.phpunit.xml', array($sniffCode));
     self::$phpcs->setIgnorePatterns(array());
     $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 (empty($failureMessages) === false) {
         $this->fail(implode(PHP_EOL, $failureMessages));
     }
 }
Beispiel #9
0
 /**
  * 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();
     }
     if ($values['generator'] !== '') {
         $phpcs = new PHP_CodeSniffer($values['verbosity']);
         $phpcs->generateDocs($values['standard'], $values['files'], $values['generator']);
         exit(0);
     }
     $fileContents = '';
     if (empty($values['files']) === true) {
         // Check if they passing in the file contents.
         $handle = fopen('php://stdin', 'r');
         $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);
         }
     }
     $values['standard'] = $this->validateStandard($values['standard']);
     if (PHP_CodeSniffer::isInstalledStandard($values['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 "' . $values['standard'] . '" coding standard is not installed. ';
         $this->printInstalledStandards();
         exit(2);
     }
     $phpcs = new PHP_CodeSniffer($values['verbosity'], $values['tabWidth'], $values['encoding'], $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) {
         $phpcs->setIgnorePatterns($values['ignored']);
     }
     // 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'];
     }
     $phpcs->setCli($this);
     $phpcs->process($values['files'], $values['standard'], $values['sniffs'], $values['local']);
     if ($fileContents !== '') {
         $phpcs->processFile('STDIN', $fileContents);
     }
     return $this->printErrorReport($phpcs, $values['reports'], $values['showSources'], $values['reportFile'], $values['reportWidth']);
 }
Beispiel #10
0
 /**
  * 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);
 }
Beispiel #11
0
 /**
  * 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']);
 }
 * @package    local_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, 'interactive' => false), array('h' => 'help', 'i' => 'interactive'));
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;
}
$interactive = false;
if ($options['interactive']) {
    $interactive = true;
}
raise_memory_limit(MEMORY_HUGE);
$standard = $CFG->dirroot . str_replace('/', DIRECTORY_SEPARATOR, '/local/codechecker/moodle');
$cli = new local_codechecker_codesniffer_cli();
$phpcs = new PHP_CodeSniffer(1, 0, 'utf-8', $interactive);
$phpcs->setCli($cli);
$phpcs->setIgnorePatterns(local_codesniffer_get_ignores());
$phpcs->process(local_codechecker_clean_path($CFG->dirroot . '/' . trim($path, '/')), local_codechecker_clean_path($standard));
$phpcs->reporting->printReport('full', false, $cli->getCommandLineValues(), null);
 /**
  * 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' : ''));
     }
 }
Beispiel #15
0
 /**
  * Runs PHP_CodeSniffer over files are 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();
     }
     if ($values['generator'] !== '') {
         $phpcs = new PHP_CodeSniffer($values['verbosity']);
         $phpcs->generateDocs($values['standard'], $values['files'], $values['generator']);
         exit(0);
     }
     if (empty($values['files']) === true) {
         echo 'ERROR: You must supply at least one file or directory to process.' . PHP_EOL . PHP_EOL;
         $this->printUsage();
         exit(2);
     }
     $values['standard'] = $this->validateStandard($values['standard']);
     if (PHP_CodeSniffer::isInstalledStandard($values['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 "' . $values['standard'] . '" coding standard is not installed. ';
         $this->printInstalledStandards();
         exit(2);
     }
     $phpcs = new PHP_CodeSniffer($values['verbosity'], $values['tabWidth']);
     // 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) {
         $phpcs->setIgnorePatterns($values['ignored']);
     }
     $phpcs->process($values['files'], $values['standard'], $values['sniffs'], $values['local']);
     return $this->printErrorReport($phpcs, $values['report'], $values['showWarnings'], $values['showSources'], $values['reportFile']);
 }
 /**
  * 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' : ''));
     }
 }
 /**
  * Tests the extending classes Sniff class.
  *
  * @return void
  * @throws PHPUnit_Framework_Error
  */
 protected final function runTest()
 {
     // 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 class name of the sniff we are testing.
     $sniffClass = str_replace('_Tests_', '_Sniffs_', $basename) . 'Sniff';
     if (is_file(dirname(__FILE__) . '/../../CodeSniffer.php') === true) {
         // We have not been installed.
         $standardsDir = realpath(dirname(__FILE__) . '/../../CodeSniffer/Standards');
         $testFileBase = $standardsDir . '/' . str_replace('_', '/', $basename) . 'UnitTest.';
     } else {
         // The name of the dummy file we are testing.
         $testFileBase = dirname(__FILE__) . '/' . str_replace('_', '/', $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, '/'));
     $di = new DirectoryIterator($dir);
     foreach ($di as $file) {
         $path = $file->getPathname();
         if (substr($path, 0, strlen($testFileBase)) === $testFileBase) {
             if ($path !== $testFileBase . 'php') {
                 $testFiles[] = $path;
             }
         }
     }
     // Get them in order. This is particularly important for multi-file sniffs.
     sort($testFiles);
     $failureMessages = array();
     $multiFileSniff = false;
     foreach ($testFiles as $testFile) {
         try {
             self::$phpcs->process(array(), $standardName, array($sniffClass));
             self::$phpcs->setIgnorePatterns(array());
             self::$phpcs->processFile($testFile);
             self::$phpcs->processMulti();
         } catch (Exception $e) {
             $this->fail('An unexpected exception has been caught: ' . $e->getMessage());
         }
         // After processing a file, check if the sniff was actually
         // a multi-file sniff (i.e., had no individual file sniffs).
         // If it is, we can skip checking of the other files and
         // do a single multi-file check.
         $sniffs = self::$phpcs->getTokenSniffs();
         if (empty($sniffs['file']) === true) {
             $multiFileSniff = true;
             break;
         }
         $files = self::$phpcs->getFiles();
         if (empty($files) === true) {
             // File was skipped for some reason.
             echo "Skipped: {$testFile}\n";
             $this->markTestSkipped();
         }
         $file = array_pop($files);
         $failures = $this->generateFailureMessages($file);
         $failureMessages = array_merge($failureMessages, $failures);
     }
     //end foreach
     if ($multiFileSniff === true) {
         try {
             self::$phpcs->process(array(), $standardName, array($sniffClass));
             self::$phpcs->setIgnorePatterns(array());
             foreach ($testFiles as $testFile) {
                 self::$phpcs->processFile($testFile);
             }
             self::$phpcs->processMulti();
         } catch (Exception $e) {
             $this->fail('An unexpected exception has been caught: ' . $e->getMessage());
         }
         $files = self::$phpcs->getFiles();
         if (empty($files) === true) {
             // File was skipped for some reason.
             $this->markTestSkipped();
         } else {
             foreach ($files as $file) {
                 $failures = $this->generateFailureMessages($file);
                 $failureMessages = array_merge($failureMessages, $failures);
             }
         }
     }
     //end if
     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();
     }
     // 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));
     }
 }
Beispiel #19
0
 /**
  * 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);
 }