2017-11-12 17 views
1

PHP_CodeSniffer에 명령 줄을 실행하는 대신 사용할 수있는 API가 있습니까?PHP_CodeSniffer 용 API가 있습니까?

그래서 PHP 코드, $ 코드 및 PHP_CodeSniffer 코드의 작곡가 보장로드의 문자열 주어, 내가 할 수있는 일이있다 등 :

// Pseudocode! 
$code_sniffer = new PHPCodeSniffer; 
$result = $code_sniffer->sniff($code); 

같은 명령 행을 통해 이동보다는 :

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

답변

1

더 많은 코드가 필요합니다.

여기 예를 살펴 것은 : https://gist.github.com/gsherwood/aafd2c16631a8a872f0c4a23916962ac 예는 아직 파일에 기록하고, 사용하는 표준 같은 것들을 설정되지 않은 코드 조각을 도청 할 수 있다는

(도 될 수있다 ruleset.xml 파일).

또 다른 예는, 그 대신 PHP +의 JS 토크 나이를 사용하는 기존 파일에서 내용을 가져옵니다, 여기에 있습니다 : https://gist.github.com/gsherwood/f17cfc90f14a9b29eeb6b2e99e6e7f66

는 많은 옵션을 사용하지 않기 때문에이 짧습니다.

+0

감사합니다! 그것은 PHPCS 3에 대한 것처럼 보입니다. 불행히도, 제가 사용하는 표준은 여전히 ​​2입니다. 그래서 그것을 알아 내야했습니다. 나는 새로운 대답으로 일하고있는 것을 게시 할 것이다. – joachim

0

는 여기에 내가 PHPCS이 일하고있어 무엇 :

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);