本文整理汇总了PHP中PHP_CodeSniffer类的典型用法代码示例。如果您正苦于以下问题:PHP PHP_CodeSniffer类的具体用法?PHP PHP_CodeSniffer怎么用?PHP PHP_CodeSniffer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PHP_CodeSniffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: process
/**
* Called when one of the token types that this sniff is listening for
* is found.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where the
* token was found.
* @param int $stackPtr The position in the PHP_CodeSniffer
* file's token stack where the token
* was found.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$this->_phpCsFile = $phpcsFile;
$varRegExp = '/\\$[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*/';
$tokens = $phpcsFile->getTokens();
$content = $tokens[$stackPtr]['content'];
$matches = array();
if (preg_match_all($varRegExp, $content, $matches, PREG_OFFSET_CAPTURE) === 0) {
return;
}
foreach ($matches as $match) {
foreach ($match as $info) {
list($var, $pos) = $info;
if ($pos === 1 || $content[$pos - 1] !== '{') {
if (strpos(substr($content, 0, $pos), '{') > 0 && strpos(substr($content, 0, $pos), '}') === false) {
continue;
}
$this->_searchForBackslashes($content, $pos);
$fix = $this->_phpCsFile->addFixableError(sprintf('must surround variable %s with { }', $var), $stackPtr, 'NotSurroundedWithBraces');
if ($fix === true) {
$correctVariable = $this->_surroundVariableWithBraces($content, $pos, $var);
$this->_fixPhpCsFile($stackPtr, $correctVariable);
}
}
//end if
}
//end foreach
}
//end foreach
}
示例2: execute
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);
}
示例3: execute
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);
}
示例4: validate
/**
* 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;
}
示例5: analyze
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;
}
示例6: it_generates_the_expected_warnings_and_errors
/**
* @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);
}
示例7: sniffFile
/**
* @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;
}
示例8: executeOnPHPFile
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);
}
}
示例9: getCodeSniffer
/**
* 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;
}
示例10: execute
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;
}
示例11: showCodestyleStandards
/**
* Show the available coding standards
*
* @param array $options
*/
public function showCodestyleStandards($options = [])
{
$phpcs = new \PHP_CodeSniffer();
$standards = $phpcs->getInstalledStandards();
sort($standards);
if (!$options['no-ansi']) {
array_walk($standards, function (&$value) {
$value = "<fg=green>{$value}</fg=green>";
});
}
$last = array_pop($standards);
$this->say("Installed coding standards are " . implode(', ', $standards) . " and " . $last);
}
示例12: sniffFile
/**
* 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;
}
示例13: getSniffAnalysis
/**
* 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;
}
示例14: process
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$ignore = array(T_DOUBLE_COLON, T_OBJECT_OPERATOR, T_FUNCTION, T_CONST);
$prevToken = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true);
if (in_array($tokens[$prevToken]['code'], $ignore) === true) {
// Not a call to a PHP function.
return;
}
$function = strtolower($tokens[$stackPtr]['content']);
if ($function != 'ini_get' && $function != 'ini_set') {
return;
}
$iniToken = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, $stackPtr, null);
$filteredToken = str_replace(array('"', "'"), array("", ""), $tokens[$iniToken]['content']);
if (in_array($filteredToken, array_keys($this->newIniDirectives)) === false) {
return;
}
$error = '';
foreach ($this->newIniDirectives[$filteredToken] as $version => $present) {
if (!is_null(PHP_CodeSniffer::getConfigData('testVersion')) && version_compare(PHP_CodeSniffer::getConfigData('testVersion'), $version) <= 0) {
if ($present === true) {
$error .= " not available before version " . $version;
}
}
}
if (strlen($error) > 0) {
$error = "INI directive '" . $filteredToken . "' is" . $error;
$phpcsFile->addWarning($error, $stackPtr);
}
}
示例15: process
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
if (false !== strpos($phpcsFile->getFilename(), 'model') || false !== strpos($phpcsFile->getFilename(), 'form') || false !== strpos($phpcsFile->getFilename(), 'filter')) {
return null;
}
$tokens = $phpcsFile->getTokens();
$className = $phpcsFile->findNext(T_STRING, $stackPtr);
$name = trim($tokens[$className]['content']);
// "op" prefix
if (0 !== strpos($name, 'op')) {
$error = ucfirst($tokens[$stackPtr]['content']) . ' name must begin with "op" prefix';
$phpcsFile->addError($error, $stackPtr);
}
// "Interface" suffix
if ($tokens[$stackPtr]['code'] === T_INTERFACE && !preg_match('/Interface$/', $name)) {
$error = ucfirst($tokens[$stackPtr]['content']) . ' name must end with "Interface"';
$phpcsFile->addError($error, $stackPtr);
}
// stripped prefix
if (0 === strpos($name, 'op')) {
$name = substr($name, 2);
}
if (!PHP_CodeSniffer::isCamelCaps($name, true, true, false)) {
$error = ucfirst($tokens[$stackPtr]['content']) . ' name is not in camel caps format';
$phpcsFile->addError($error, $stackPtr);
}
}