processFile() public method

Processes the file and runs the PHP_CodeSniffer sniffs to verify that it conforms with the standard. Returns the processed file object, or NULL if no file was processed due to error.
See also: _processFile()
public processFile ( string $file, string $contents = null ) : PHP_CodeSniffer_File
$file string The file to process.
$contents string The contents to parse. If NULL, the content is taken from the file system.
return PHP_CodeSniffer_File
 /**
  * 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));
     }
 }
 /**
  * Sniff a file and return resulting file object
  *
  * @param string $filename Filename to sniff
  * @param string $targetPhpVersion Value of 'testVersion' to set on PHPCS object
  * @return PHP_CodeSniffer_File File object
  */
 public function sniffFile($filename, $targetPhpVersion = null)
 {
     if (null !== $targetPhpVersion) {
         PHP_CodeSniffer::setConfigData('testVersion', $targetPhpVersion, true);
     }
     $filename = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . $filename;
     try {
         $phpcsFile = self::$phpcs->processFile($filename);
     } catch (Exception $e) {
         $this->fail('An unexpected exception has been caught: ' . $e->getMessage());
         return false;
     }
     return $phpcsFile;
 }
 /**
  * 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));
     }
 }
 protected static function analyze(array $sniffs, $files)
 {
     $sniffs = array_map(static function ($sniff) {
         $sniff = __DIR__ . '/../../../../src/' . $sniff . '.php';
         static::assertFileExists($sniff, 'Sniff does not exist');
         return $sniff;
     }, $sniffs);
     $files = array_map(static function ($file) {
         static::assertFileExists($file, 'Source file does not exists');
         return $file;
     }, (array) $files);
     $codeSniffer = new PHP_CodeSniffer();
     $codeSniffer->registerSniffs($sniffs, []);
     $codeSniffer->populateTokenListeners();
     $report = [];
     foreach ($files as $file) {
         $phpcsFile = $codeSniffer->processFile($file);
         $report[$file] = [];
         $report[$file]['numWarnings'] = $phpcsFile->getWarningCount();
         $report[$file]['warnings'] = $phpcsFile->getWarnings();
         $report[$file]['numErrors'] = $phpcsFile->getErrorCount();
         $report[$file]['errors'] = $phpcsFile->getErrors();
     }
     return $report;
 }
 /**
  * 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));
     }
 }
 /**
  * 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));
     }
 }
Beispiel #8
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;
 }
 /**
  * @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);
 }
 /**
  * @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;
 }
Beispiel #11
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);
     }
 }
Beispiel #12
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 #13
0
 public function processFile($file, $contents = null)
 {
     if ($this->_cacheable) {
         // If we have cached results and they're not stale, don't bother processing
         $cacheTime = $this->_dbFiles->getTimeParsed($file);
         $mtime = filemtime($file);
         if ($cacheTime !== null && $cacheTime > $mtime) {
             return;
         }
     }
     parent::processFile($file, $contents);
     if ($this->_cacheable) {
         $this->_dbFiles->registerFile($file);
     }
 }
 /**
  * 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 #16
0
 /**
  * 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);
 }
 /**
  * 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));
     }
 }
Beispiel #18
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']);
 }
 /**
  * Test suppressing a whole file.
  *
  * @return void
  */
 public function testSuppressFile()
 {
     $phpcs = new PHP_CodeSniffer();
     $phpcs->setTokenListeners('Squiz', array('Generic_Sniffs_Commenting_TodoSniff'));
     $phpcs->populateTokenListeners();
     // Process without suppression.
     $content = '<?php ' . PHP_EOL . '//TODO: write some code';
     $phpcs->processFile('noSuppressionTest.php', $content);
     $files = $phpcs->getFiles();
     $file = $files[0];
     $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';
     $phpcs->processFile('suppressionTest.php', $content);
     $files = $phpcs->getFiles();
     $file = $files[1];
     $warnings = $file->getWarnings();
     $numWarnings = $file->getWarningCount();
     $this->assertEquals(0, $numWarnings);
     $this->assertEquals(0, count($warnings));
 }
 /**
  * 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;
 }
 /**
  * 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));
     }
 }
 /**
  * Test suppressing a whole file.
  *
  * @return void
  */
 public function testSuppressFile()
 {
     $phpcs = new PHP_CodeSniffer();
     $phpcs->setTokenListeners('Squiz', array('Squiz_Sniffs_Commenting_FileCommentSniff'));
     $phpcs->populateTokenListeners();
     // Process without suppression.
     $content = '<?php ' . PHP_EOL . '$var = FALSE;';
     $phpcs->processFile('noSuppressionTest.php', $content);
     $files = $phpcs->getFiles();
     $file = $files[0];
     $errors = $file->getErrors();
     $numErrors = $file->getErrorCount();
     $this->assertEquals(1, $numErrors);
     $this->assertEquals(1, count($errors));
     $this->assertEquals(1, count($files));
     // Process with suppression.
     $content = '<?php ' . PHP_EOL . '// @codingStandardsIgnoreFile' . PHP_EOL . '$var = FALSE;';
     $phpcs->processFile('suppressionTest.php', $content);
     // The file shouldn't even be added to the $files array.
     $files = $phpcs->getFiles();
     $this->assertEquals(1, count($files));
 }
 private function process($files, $interactive = true)
 {
     $standards = 'Webasyst';
     if (PHP_CodeSniffer::isInstalledStandard($standards) === false) {
         $this->tracef('WARNING: %s standard not found, will used PSR2. Some rules are differ', $standards);
         $standards = 'PSR2';
     }
     if (is_array($standards) === false) {
         $standards = array($standards);
     }
     $phpcs = new PHP_CodeSniffer(0, 4, 'UTF-8', $interactive);
     // Set file extensions if they were specified. Otherwise,
     // let PHP_CodeSniffer decide on the defaults.
     if (true) {
         $extensions = array('php', 'js', 'css');
         $phpcs->setAllowedFileExtensions($extensions);
     }
     if (is_array($files) === false) {
         $files = array($files);
     }
     // Reset the members.
     // Ensure this option is enabled or else line endings will not always
     // be detected properly for files created on a Mac with the /r line ending.
     ini_set('auto_detect_line_endings', true);
     $sniffs = array();
     foreach ($standards as $standard) {
         $installed = $phpcs->getInstalledStandardPath($standard);
         if ($installed !== null) {
             $standard = $installed;
         } else {
             if (is_dir($standard) === true && is_file(realpath($standard . '/ruleset.xml')) === true) {
                 $standard = realpath($standard . '/ruleset.xml');
             }
         }
         $sniffs = array_merge($sniffs, $phpcs->processRuleset($standard));
     }
     //end foreach
     $sniffRestrictions = array();
     $phpcs->registerSniffs($sniffs, $sniffRestrictions);
     $phpcs->populateTokenListeners();
     // The SVN pre-commit calls process() to init the sniffs
     // and ruleset so there may not be any files to process.
     // But this has to come after that initial setup.
     //define('PHP_CODESNIFFER_IN_TESTS',true);
     $_SERVER['argc'] = 0;
     $errors_count = 0;
     foreach ($files as $file) {
         $phpcsFile = $phpcs->processFile($file);
         // Show progress information.
         if ($phpcsFile !== null) {
             $count = $phpcsFile->getErrorCount() + $phpcsFile->getWarningCount();
             if (!$interactive && $count) {
                 $report = array('ERROR' => $phpcsFile->getErrors(), 'WARNING' => $phpcsFile->getWarnings());
                 $this->tracef("\nFILE: %s", str_replace($this->path . '/', '', $file));
                 $this->trace(str_repeat('-', 80));
                 foreach ($report as $type => $errors) {
                     foreach ($errors as $line => $line_errors) {
                         foreach ($line_errors as $column => $errors) {
                             foreach ($errors as $error) {
                                 $this->tracef('%4d | %s | %s', $line, $type, $error['message']);
                             }
                         }
                     }
                 }
                 $this->trace(str_repeat('-', 80));
             }
             $errors_count += $count;
         }
     }
     return $errors_count;
 }
 /**
  * CodeSnifferShell::_getTokens()
  *
  * @param string $path
  * @return array Tokens
  */
 protected function _getTokens($path)
 {
     include_once 'PHP/CodeSniffer.php';
     $phpcs = new PHP_CodeSniffer();
     $phpcs->process([], $this->standard, []);
     $file = $phpcs->processFile($path);
     $file->start();
     return $file->getTokens();
 }
Beispiel #25
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']);
 }
 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;
 }
 /**
  * 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));
 }
Beispiel #28
0
 /**
  * @param string $filename
  * @param string $extension
  * @param string $fileContent
  * @return array
  */
 public function processFile($filename, $extension, $fileContent)
 {
     $phpCsResult = $this->phpcs->processFile($filename, $fileContent);
     $errors = $phpCsResult->getErrors();
     return $errors;
 }