有PHP_CodeSniffer的API吗?

有PHP_CodeSniffer的API吗?,php,phpcodesniffer,Php,Phpcodesniffer,PHP_CodeSniffer是否有可以使用的API,而不是运行命令行 因此,给定一个PHP代码字符串、$code和确保加载PHP_CodeSniffer代码的Composer,我是否可以执行以下操作: // Pseudocode! $code_sniffer = new PHPCodeSniffer; $result = $code_sniffer->sniff($code); 而不是通过命令行执行以下操作: $result = exec(sprintf('echo %s | vend

PHP_CodeSniffer是否有可以使用的API,而不是运行命令行

因此,给定一个PHP代码字符串、$code和确保加载PHP_CodeSniffer代码的Composer,我是否可以执行以下操作:

// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);
而不是通过命令行执行以下操作:

$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));

确实有,但您需要编写更多的代码

请看下面的示例:

该示例允许您嗅探尚未写入文件的代码片段,并设置要使用的标准(也可以是ruleset.xml文件)

另一个使用JS标记器而不是PHP+从现有文件中提取内容的示例如下:


它之所以更短,是因为它没有使用太多的选项。

以下是我为PHPCS 2所做的工作:

PHP_CodeSniffer::setConfigData(
  'installed_paths',
  // The path to the standard I am using.
  __DIR__ . '/../../vendor/drupal/coder/coder_sniffer',
  TRUE
);


$phpcs = new PHP_CodeSniffer(
  // Verbosity.
  0,
  // Tab width
  0,
  // Encoding.
  'iso-8859-1',
  // Interactive.
  FALSE
);

$phpcs->initStandard('Drupal');

// Mock a PHP_CodeSniffer_CLI object, as the PHP_CodeSniffer object expects
// to have this and be able to retrieve settings from it.
// (I am using PHPCS within tests, so I have Prophecy available to do this. In another context, just creating a subclass of PHP_CodeSniffer_CLI set to return the right things would work too.) 
$prophet = new \Prophecy\Prophet;
$prophecy = $prophet->prophesize();
$prophecy->willExtend(\PHP_CodeSniffer_CLI::class);
// No way to set these on the phpcs object.
$prophecy->getCommandLineValues()->willReturn([
  'reports' => [
    "full" => NULL,
  ],
  "showSources" => false,
  "reportWidth" => null,
  "reportFile" => null
]);
$phpcs_cli = $prophecy->reveal();
// Have to set these properties, as they are read directly, e.g. by
// PHP_CodeSniffer_File::_addError()
$phpcs_cli->errorSeverity = 5;
$phpcs_cli->warningSeverity = 5;

// Set the CLI object on the PHP_CodeSniffer object.
$phpcs->setCli($phpcs_cli);

// Process the file with PHPCS.
$phpcsFile = $phpcs->processFile(NULL, $code);

$errors   = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();

$total_error_count = ($phpcsFile->getErrorCount() + $phpcsFile->getWarningCount());

// Get the reporting to process the errors.
$this->reporting = new \PHP_CodeSniffer_Reporting();
$reportClass = $this->reporting->factory('full');

// This gets you an array of all the messages which you can easily work over.
$reportData  = $this->reporting->prepareFileReport($phpcsFile);

// This formats the report, but prints it directly.
$reportClass->generateFileReport($reportData, $phpcsFile);

谢谢这看起来像是为PHPCS3准备的。不幸的是,我现在使用的标准仍然是2,所以我必须找出它的原因。我将把我得到的作为一个新答案发布。