process() public method

Start a PHP_CodeSniffer run.
public process ( string | array $files, string | array $standards, array $restrictions = [], boolean $local = false ) : void
$files string | array The files and directories to process. For directories, each sub directory will also be traversed for source files.
$standards string | array The set of code sniffs we are testing against.
$restrictions array The sniff codes to restrict the violations to.
$local boolean If true, don't recurse into directories.
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.
  *
  * @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));
     }
 }
Beispiel #4
0
 public function execute()
 {
     require_once $this->mooshDir . "/includes/codesniffer_cli.php";
     require_once $this->mooshDir . "/includes/coderepair/CodeRepair.php";
     $moodle_sniffs = $this->mooshDir . "/vendor/moodlerooms/moodle-coding-standard/moodle";
     $options = $this->expandedOptions;
     $interactive = $options['interactive'];
     if (isset($options['path'])) {
         $this->checkDirArg($options['path']);
         $path = $options['path'];
     } else {
         $path = $this->cwd;
     }
     $files = $this->_get_files($path);
     if ($options['repair'] === true) {
         $code_repair = new \CodeRepair($files);
         $code_repair->drymode = false;
         $code_repair->start();
     }
     $phpcscli = new \codesniffer_cli();
     $phpcs = new \PHP_CodeSniffer(1, 0, 'utf-8', (bool) $interactive);
     $phpcs->setCli($phpcscli);
     $phpcs->process($files, $moodle_sniffs);
     $phpcs->reporting->printReport('full', false, $phpcscli->getCommandLineValues(), null);
 }
 /**
  * Process analysis with framework standard
  * 
  * @param  string $file
  * @see    parent::process()
  * 
  * @return bool
  */
 function process($file)
 {
     $root_dir = CAppUI::conf("root_dir");
     $file = "{$root_dir}/{$file}";
     $standard = $this->getStandardDir();
     parent::process($file, $standard);
 }
Beispiel #6
0
 /**
  * Validate the current check
  *
  * Validate the check on the specified repository. Returns an array of 
  * found issues.
  * 
  * @param pchRepository $repository 
  * @return void
  */
 public function validate(pchRepository $repository)
 {
     $cs = new PHP_CodeSniffer();
     $cs->process(array(), $this->standard);
     foreach ($this->getChangedFiles($repository) as $file) {
         $cs->processFile($file, stream_get_contents($this->getFileContents($repository, $file)));
     }
     $issues = array();
     foreach ($cs->getFilesErrors() as $file => $messages) {
         foreach ($messages['errors'] as $errors) {
             foreach ($errors as $line => $lineErrors) {
                 foreach ($lineErrors as $error) {
                     $issues[] = new pchIssue(E_ERROR, $file, $line, $error['source'] . ': ' . $error['message']);
                 }
             }
         }
         foreach ($messages['warnings'] as $errors) {
             foreach ($errors as $line => $lineErrors) {
                 foreach ($lineErrors as $error) {
                     $issues[] = new pchIssue(E_WARNING, $file, $line, $error['source'] . ': ' . $error['message']);
                 }
             }
         }
     }
     return $issues;
 }
Beispiel #7
0
 public function execute()
 {
     require_once $this->mooshDir . "/includes/codesniffer/CodeSniffer.php";
     require_once $this->mooshDir . "/includes/codesniffer/lib.php";
     require_once $this->mooshDir . "/includes/coderepair/CodeRepair.php";
     $moodle_sniffs = $this->mooshDir . "/includes/codesniffer/moodle";
     $options = $this->expandedOptions;
     $interactive = $options['interactive'];
     if (isset($options['path'])) {
         $this->checkFileArg($options['path']);
         $path = $options['path'];
     } else {
         $path = $this->cwd;
     }
     $files = $this->_get_files($path);
     if ($options['repair'] === true) {
         $code_repair = new \CodeRepair($files);
         $code_repair->drymode = false;
         $code_repair->start();
     }
     $phpcs = new \PHP_CodeSniffer(1, 0, 'utf-8', false);
     $phpcs->setCli(new \codesniffer_cli());
     $numerrors = $phpcs->process($files, $moodle_sniffs);
     $phpcs->reporting->printReport('full', false, null);
 }
 /**
  * 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));
     }
 }
 /**
  * @test
  * @dataProvider fixturesProvider
  */
 public function it_generates_the_expected_warnings_and_errors($file, array $expectedErrors, array $expectedWarnings)
 {
     $codeSniffer = new \PHP_CodeSniffer();
     $codeSniffer->process(array(), $this->getRulesetXmlPath(), array($this->getRuleName()));
     $sniffedFile = $codeSniffer->processFile($file);
     $this->fileHasExpectedErrors($sniffedFile, $expectedErrors);
     $this->fileHasExpectedWarnings($sniffedFile, $expectedWarnings);
 }
Beispiel #10
0
 protected function executeOnPHPFile(File $file)
 {
     $code_sniffer = new \PHP_CodeSniffer($this->phpcs_verbosity, $this->phpcs_tab_width, $this->phpcs_encoding, self::PHPCS_NOT_INTERACTIVE_MODE);
     //Load the standard
     $code_sniffer->process(array(), $this->standard, array());
     $file_result = $code_sniffer->processFile($file->getPath(), $file->getContent());
     if ($file_result->getErrorCount()) {
         $this->handlePHPCSErrors($file, $file_result);
     }
 }
 /**
  * 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;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->outputHeading($output, 'Moodle Code Checker on %s');
     $files = $this->plugin->getFiles($this->finder);
     if (count($files) === 0) {
         return $this->outputSkip($output);
     }
     $sniffer = new \PHP_CodeSniffer();
     $sniffer->setCli(new CodeSnifferCLI(['reports' => ['full' => null], 'colors' => true, 'encoding' => 'utf-8', 'showProgress' => true, 'reportWidth' => 120]));
     $sniffer->process($files, $this->standard);
     $results = $sniffer->reporting->printReport('full', false, $sniffer->cli->getCommandLineValues(), null, 120);
     return $results['errors'] > 0 ? 1 : 0;
 }
 /**
  * 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));
     }
 }
Beispiel #14
0
 /**
  * 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->process(array(), 'coder_sniffer/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);
     }
     //end foreach
     if (empty($failureMessages) === false) {
         $this->fail(implode(PHP_EOL, $failureMessages));
     }
 }
Beispiel #15
0
 /**
  * Run the task.
  *
  * @param array &$options Additional options.
  *
  * @return integer Number of errors.
  */
 public function run(&$options)
 {
     $old_dir = getcwd();
     $lib = realpath($this->_config->getPath() . '/lib');
     $argv = $_SERVER['argv'];
     $argc = $_SERVER['argv'];
     $_SERVER['argv'] = array();
     $_SERVER['argc'] = 0;
     define('PHPCS_DEFAULT_WARN_SEV', 0);
     $phpcs = new PHP_CodeSniffer();
     $phpcs->process($lib, Components_Constants::getDataDirectory() . '/qc_standards/phpcs.xml');
     $_SERVER['argv'] = $argv;
     $_SERVER['argc'] = $argc;
     chdir($old_dir);
     return $phpcs->reporting->printReport('emacs', false, null);
 }
 /**
  * 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 #17
0
 /**
  * 実行
  *
  * @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();
     }
 }
Beispiel #18
0
 /**
  * Returns a list of paths to XML standard files for all sniffs in a standard.
  *
  * Any sniffs that do not have an XML standard file are obviously not included
  * in the returned array. If documentation is only being generated for some
  * sniffs (ie. $this->_sniffs is not empty) then all others sniffs will
  * be filtered from the results as well.
  *
  * @return string[]
  */
 protected function getStandardFiles()
 {
     $phpcs = new PHP_CodeSniffer();
     $phpcs->process(array(), $this->_standard);
     $sniffs = $phpcs->getSniffs();
     $standardFiles = array();
     foreach ($sniffs as $className => $sniffClass) {
         $object = new ReflectionObject($sniffClass);
         $sniff = $object->getFilename();
         if (empty($this->_sniffs) === false) {
             // We are limiting the docs to certain sniffs only, so filter
             // out any unwanted sniffs.
             $parts = explode('_', $className);
             $sniffName = $parts[0] . '.' . $parts[2] . '.' . substr($parts[3], 0, -5);
             if (in_array($sniffName, $this->_sniffs) === false) {
                 continue;
             }
         }
         $standardFile = str_replace(DIRECTORY_SEPARATOR . 'Sniffs' . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR . 'Docs' . DIRECTORY_SEPARATOR, $sniff);
         $standardFile = str_replace('Sniff.php', 'Standard.xml', $standardFile);
         if (is_file($standardFile) === true) {
             $standardFiles[] = $standardFile;
         }
     }
     //end foreach
     return $standardFiles;
 }
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);
 }
Beispiel #20
0
 /**
  * Prints a report showing the sniffs contained in a standard.
  *
  * @param string $standard The standard to validate.
  *
  * @return void
  */
 public function explainStandard($standard)
 {
     $phpcs = new PHP_CodeSniffer();
     $phpcs->process(array(), $standard);
     $sniffs = $phpcs->getSniffs();
     $sniffs = array_keys($sniffs);
     sort($sniffs);
     ob_start();
     $lastStandard = '';
     $lastCount = '';
     $sniffCount = count($sniffs);
     $sniffs[] = '___';
     echo PHP_EOL . "The {$standard} standard contains {$sniffCount} sniffs" . PHP_EOL;
     ob_start();
     foreach ($sniffs as $sniff) {
         $parts = explode('_', str_replace('\\', '_', $sniff));
         if ($lastStandard === '') {
             $lastStandard = $parts[0];
         }
         if ($parts[0] !== $lastStandard) {
             $sniffList = ob_get_contents();
             ob_end_clean();
             echo PHP_EOL . $lastStandard . ' (' . $lastCount . ' sniffs)' . PHP_EOL;
             echo str_repeat('-', strlen($lastStandard . $lastCount) + 10);
             echo PHP_EOL;
             echo $sniffList;
             $lastStandard = $parts[0];
             $lastCount = 0;
             ob_start();
         }
         echo '  ' . $parts[0] . '.' . $parts[2] . '.' . substr($parts[3], 0, -5) . PHP_EOL;
         $lastCount++;
     }
     //end foreach
     ob_end_clean();
 }
 * @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 #24
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']);
 }
 public function sniffList()
 {
     if (!class_exists('PHP_CodeSniffer')) {
         $composerInstall = dirname(dirname(dirname(__FILE__))) . '/vendor/squizlabs/php_codesniffer/CodeSniffer.php';
         if (file_exists($composerInstall)) {
             require_once $composerInstall;
         } else {
             require_once 'PHP/CodeSniffer.php';
         }
     }
     $phpcs = new PHP_CodeSniffer();
     $phpcs->process(array(), $this->codingStandardName);
     $sniffs = $phpcs->getSniffs();
     $sniffs = array_keys($sniffs);
     sort($sniffs);
     $sniffList = [];
     foreach ($sniffs as $sniff) {
         $parts = explode('_', str_replace('\\', '_', $sniff));
         $sniffList[] = "{$parts[0]}.{$parts[2]}." . substr($parts[3], 0, -5);
     }
     return $sniffList;
 }
 /**
  * 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($testFile, $standardName, array($sniffClass));
         } 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 indivdual 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();
         $file = array_pop($files);
         $failures = $this->generateFailureMessages($file, $testFile);
         $failureMessages = array_merge($failureMessages, $failures);
     }
     //end foreach
     if ($multiFileSniff === true) {
         try {
             self::$phpcs->process($testFiles, $standardName, array($sniffClass));
         } catch (Exception $e) {
             $this->fail('An unexpected exception has been caught: ' . $e->getMessage());
         }
         $files = self::$phpcs->getFiles();
         foreach ($files as $file) {
             $failures = $this->generateFailureMessages($file);
             $failureMessages = array_merge($failureMessages, $failures);
         }
     }
     if (empty($failureMessages) === false) {
         $this->fail(implode(PHP_EOL, $failureMessages));
     }
 }
Beispiel #27
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 #28
0
 public function process($files, $local = false, $cacheable = false)
 {
     $this->_cacheable = $cacheable;
     parent::process($files, $local);
 }
 /**
  * Test suppressing a whole file.
  *
  * @return void
  */
 public function testSuppressFile()
 {
     $phpcs = new PHP_CodeSniffer();
     $phpcs->process(array(), '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));
 }
 /**
  * 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' : ''));
     }
 }