PHP_CodeSniffer是否有我可以使用的API,而不是运行命令行?
所以给定一串PHP代码,$ code和Composer确保加载PHP_CodeSniffer代码,我可以做些什么,如:
// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);
而不是通过命令行使用:
$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));
答案 0 :(得分:1)
有,但你需要编写更多的代码。
看一下这里的示例:https://gist.github.com/gsherwood/aafd2c16631a8a872f0c4a23916962ac
该示例允许您嗅探尚未写入文件的一段代码,并设置类似要使用的标准(也可以是ruleset.xml文件)。
另一个使用JS tokenizer而不是PHP +从现有文件中提取内容的示例可在此处获取:https://gist.github.com/gsherwood/f17cfc90f14a9b29eeb6b2e99e6e7f66
它更短,因为它没有使用尽可能多的选项。
答案 1 :(得分:0)
以下是我为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);