1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
|
<?php
/*
* $Id: acbef5e46dea2c4963c4bf345cfb35cf5779d735 $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/Task.php';
/**
* A PHP code sniffer task. Checking the style of one or more PHP source files.
*
* @author Dirk Thomas <dirk.thomas@4wdmedia.de>
* @version $Id: acbef5e46dea2c4963c4bf345cfb35cf5779d735 $
* @package phing.tasks.ext
*/
class PhpCodeSnifferTask extends Task {
protected $file; // the source file (from xml attribute)
protected $filesets = array(); // all fileset objects assigned to this task
// parameters for php code sniffer
protected $standard = 'Generic';
protected $sniffs = array();
protected $showWarnings = true;
protected $showSources = false;
protected $reportWidth = 80;
protected $verbosity = 0;
protected $tabWidth = 0;
protected $allowedFileExtensions = array('php', 'inc', 'js', 'css');
protected $ignorePatterns = false;
protected $noSubdirectories = false;
protected $configData = array();
protected $encoding = 'iso-8859-1';
// parameters to customize output
protected $showSniffs = false;
protected $format = 'full';
protected $formatters = array();
/**
* Holds the type of the doc generator
*
* @var string
*/
protected $docGenerator = '';
/**
* Holds the outfile for the documentation
*
* @var PhingFile
*/
protected $docFile = null;
private $haltonerror = false;
private $haltonwarning = false;
private $skipversioncheck = false;
/**
* Load the necessary environment for running PHP_CodeSniffer.
*
* @return void
*/
public function init()
{
}
/**
* File to be performed syntax check on
* @param PhingFile $file
*/
public function setFile(PhingFile $file) {
$this->file = $file;
}
/**
* Nested adder, adds a set of files (nested fileset attribute).
*
* @return void
*/
public function addFileSet(FileSet $fs) {
$this->filesets[] = $fs;
}
/**
* Sets the coding standard to test for
*
* @param string $standard The coding standard
*
* @return void
*/
public function setStandard($standard)
{
$this->standard = $standard;
}
/**
* Sets the sniffs which the standard should be restricted to
* @param string $sniffs
*/
public function setSniffs($sniffs)
{
$token = ' ,;';
$sniff = strtok($sniffs, $token);
while ($sniff !== false) {
$this->sniffs[] = $sniff;
$sniff = strtok($token);
}
}
/**
* Sets the type of the doc generator
*
* @param string $generator HTML or Text
*
* @return void
*/
public function setDocGenerator($generator)
{
$this->docGenerator = $generator;
}
/**
* Sets the outfile for the documentation
*
* @param PhingFile $file The outfile for the doc
*
* @return void
*/
public function setDocFile(PhingFile $file)
{
$this->docFile = $file;
}
/**
* Sets the flag if warnings should be shown
* @param boolean $show
*/
public function setShowWarnings($show)
{
$this->showWarnings = StringHelper::booleanValue($show);
}
/**
* Sets the flag if sources should be shown
*
* @param boolean $show Whether to show sources or not
*
* @return void
*/
public function setShowSources($show)
{
$this->showSources = StringHelper::booleanValue($show);
}
/**
* Sets the width of the report
*
* @param int $width How wide the screen reports should be.
*
* @return void
*/
public function setReportWidth($width)
{
$this->reportWidth = (int) $width;
}
/**
* Sets the verbosity level
* @param int $level
*/
public function setVerbosity($level)
{
$this->verbosity = (int)$level;
}
/**
* Sets the tab width to replace tabs with spaces
* @param int $width
*/
public function setTabWidth($width)
{
$this->tabWidth = (int)$width;
}
/**
* Sets file encoding
* @param string $encoding
*/
public function setEncoding($encoding)
{
$this->encoding = $encoding;
}
/**
* Sets the allowed file extensions when using directories instead of specific files
* @param array $extensions
*/
public function setAllowedFileExtensions($extensions)
{
$this->allowedFileExtensions = array();
$token = ' ,;';
$ext = strtok($extensions, $token);
while ($ext !== false) {
$this->allowedFileExtensions[] = $ext;
$ext = strtok($token);
}
}
/**
* Sets the ignore patterns to skip files when using directories instead of specific files
* @param array $extensions
*/
public function setIgnorePatterns($patterns)
{
$this->ignorePatterns = array();
$token = ' ,;';
$pattern = strtok($patterns, $token);
while ($pattern !== false) {
$this->ignorePatterns[$pattern] = 'relative';
$pattern = strtok($token);
}
}
/**
* Sets the flag if subdirectories should be skipped
* @param boolean $subdirectories
*/
public function setNoSubdirectories($subdirectories)
{
$this->noSubdirectories = StringHelper::booleanValue($subdirectories);
}
/**
* Creates a config parameter for this task
*
* @return Parameter The created parameter
*/
public function createConfig() {
$num = array_push($this->configData, new Parameter());
return $this->configData[$num-1];
}
/**
* Sets the flag if the used sniffs should be listed
* @param boolean $show
*/
public function setShowSniffs($show)
{
$this->showSniffs = StringHelper::booleanValue($show);
}
/**
* Sets the output format
* @param string $format
*/
public function setFormat($format)
{
$this->format = $format;
}
/**
* Create object for nested formatter element.
* @return CodeSniffer_FormatterElement
*/
public function createFormatter () {
$num = array_push($this->formatters,
new PhpCodeSnifferTask_FormatterElement());
return $this->formatters[$num-1];
}
/**
* Sets the haltonerror flag
* @param boolean $value
*/
public function setHaltonerror($value)
{
$this->haltonerror = $value;
}
/**
* Sets the haltonwarning flag
* @param boolean $value
*/
public function setHaltonwarning($value)
{
$this->haltonwarning = $value;
}
/**
* Sets the skipversioncheck flag
* @param boolean $value
*/
public function setSkipVersionCheck($value)
{
$this->skipversioncheck = $value;
}
/**
* Executes PHP code sniffer against PhingFile or a FileSet
*/
public function main() {
if (!class_exists('PHP_CodeSniffer')) {
@include_once 'PHP/CodeSniffer.php';
if (!class_exists('PHP_CodeSniffer')) {
throw new BuildException("This task requires the PHP_CodeSniffer package installed and available on the include path", $this->getLocation());
}
}
/**
* Determine PHP_CodeSniffer version number
*/
if (!$this->skipversioncheck) {
if (defined('PHP_CodeSniffer::VERSION')) {
preg_match('/\d\.\d\.\d/', PHP_CodeSniffer::VERSION, $version);
} else {
preg_match('/\d\.\d\.\d/', shell_exec('phpcs --version'), $version);
}
if (version_compare($version[0], '1.2.2') < 0) {
throw new BuildException(
'PhpCodeSnifferTask requires PHP_CodeSniffer version >= 1.2.2',
$this->getLocation()
);
}
}
if(!isset($this->file) and count($this->filesets) == 0) {
throw new BuildException("Missing either a nested fileset or attribute 'file' set");
}
if (count($this->formatters) == 0) {
// turn legacy format attribute into formatter
$fmt = new PhpCodeSnifferTask_FormatterElement();
$fmt->setType($this->format);
$fmt->setUseFile(false);
$this->formatters[] = $fmt;
}
$fileList = array();
if (!isset($this->file)) {
$project = $this->getProject();
foreach ($this->filesets as $fs) {
$ds = $fs->getDirectoryScanner($project);
$files = $ds->getIncludedFiles();
$dir = $fs->getDir($this->project)->getAbsolutePath();
foreach ($files as $file) {
$fileList[] = $dir.DIRECTORY_SEPARATOR.$file;
}
}
} else {
$fileList[] = $this->file->getPath();
}
$cwd = getcwd();
// Save command line arguments because it confuses PHPCS (version 1.3.0)
$oldArgs = $_SERVER['argv'];
$_SERVER['argv'] = array();
$_SERVER['argc'] = 0;
include_once 'phing/tasks/ext/phpcs/PhpCodeSnifferTask_Wrapper.php';
$codeSniffer = new PhpCodeSnifferTask_Wrapper($this->verbosity, $this->tabWidth, $this->encoding);
$codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions);
if (is_array($this->ignorePatterns)) $codeSniffer->setIgnorePatterns($this->ignorePatterns);
foreach ($this->configData as $configData) {
$codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true);
}
/*
* Verifying if standard is installed only after setting config data.
* Custom standard paths could be provided via installed_paths config parameter.
*/
if (PHP_CodeSniffer::isInstalledStandard($this->standard) === false) {
// They didn't select a valid coding standard, so help them
// out by letting them know which standards are installed.
$installedStandards = PHP_CodeSniffer::getInstalledStandards();
$numStandards = count($installedStandards);
$errMsg = '';
if ($numStandards === 0) {
$errMsg = 'No coding standards are installed.';
} else {
$lastStandard = array_pop($installedStandards);
if ($numStandards === 1) {
$errMsg = 'The only coding standard installed is ' . $lastStandard;
} else {
$standardList = implode(', ', $installedStandards);
$standardList .= ' and ' . $lastStandard;
$errMsg = 'The installed coding standards are ' . $standardList;
}
}
throw new BuildException(
'ERROR: the "' . $this->standard . '" coding standard is not installed. ' . $errMsg,
$this->getLocation()
);
}
// nasty integration hack
$values = $codeSniffer->cli->getDefaults();
$_SERVER['argv'] = array('t');
$_SERVER['argc'] = 1;
foreach ($this->formatters as $fe) {
$output = ($fe->getUseFile() ? $fe->getOutFile() : null);
$_SERVER['argv'][]= '--report-' . $fe->getType() . '=' . $output;
$_SERVER['argc']++;
}
$codeSniffer->process($fileList, $this->standard, $this->sniffs, $this->noSubdirectories);
$_SERVER['argv'] = array();
$_SERVER['argc'] = 0;
$this->printErrorReport($codeSniffer);
// generate the documentation
if ($this->docGenerator !== '' && $this->docFile !== null) {
ob_start();
$codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator);
$output = ob_get_contents();
ob_end_clean();
// write to file
$outputFile = $this->docFile->getPath();
$check = file_put_contents($outputFile, $output);
if (is_bool($check) && !$check) {
throw new BuildException('Error writing doc to ' . $outputFile);
}
} elseif ($this->docGenerator !== '' && $this->docFile === null) {
$codeSniffer->generateDocs($this->standard, $this->sniffs, $this->docGenerator);
}
if ($this->haltonerror && $codeSniffer->reporting->totalErrors > 0) {
throw new BuildException('phpcodesniffer detected ' . $codeSniffer->reporting->totalErrors . ' error' . ($codeSniffer->reporting->totalErrors > 1 ? 's' : ''));
}
if ($this->haltonwarning && $codeSniffer->reporting->totalWarnings > 0) {
throw new BuildException('phpcodesniffer detected ' . $codeSniffer->reporting->totalWarnings . ' warning' . ($codeSniffer->reporting->totalWarnings > 1 ? 's' : ''));
}
$_SERVER['argv'] = $oldArgs;
$_SERVER['argc'] = count($oldArgs);
chdir($cwd);
}
/**
* Prints the error report.
*
* @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing
* the errors.
*/
protected function printErrorReport($phpcs)
{
if ($this->showSniffs) {
$sniffs = $phpcs->getSniffs();
$sniffStr = '';
foreach ($sniffs as $sniff) {
if (is_string($sniff)) {
$sniffStr .= '- ' . $sniff . PHP_EOL;
} else {
$sniffStr .= '- ' . get_class($sniff) . PHP_EOL;
}
}
$this->log('The list of used sniffs (#' . count($sniffs) . '): ' . PHP_EOL . $sniffStr, Project::MSG_INFO);
}
// process output
$reporting = $phpcs->reporting;
foreach ($this->formatters as $fe) {
$reportFile = null;
if ($fe->getUseFile()) {
$reportFile = $fe->getOutfile();
//ob_start();
}
$reporting->printReport(
$fe->getType(),
$this->showSources,
$reportFile,
$this->reportWidth
);
// reporting class uses ob_end_flush(), but we don't want
// an output if we use a file
if ($fe->getUseFile()) {
//ob_end_clean();
}
}
}
/**
* Outputs the results with a custom format
*
* @param array $report Packaged list of all errors in each file
*/
protected function outputCustomFormat($report) {
$files = $report['files'];
foreach ($files as $file => $attributes) {
$errors = $attributes['errors'];
$warnings = $attributes['warnings'];
$messages = $attributes['messages'];
if ($errors > 0) {
$this->log($file . ': ' . $errors . ' error' . ($errors > 1 ? 's' : '') . ' detected', Project::MSG_ERR);
$this->outputCustomFormatMessages($messages, 'ERROR');
} else {
$this->log($file . ': No syntax errors detected', Project::MSG_VERBOSE);
}
if ($warnings > 0) {
$this->log($file . ': ' . $warnings . ' warning' . ($warnings > 1 ? 's' : '') . ' detected', Project::MSG_WARN);
$this->outputCustomFormatMessages($messages, 'WARNING');
}
}
$totalErrors = $report['totals']['errors'];
$totalWarnings = $report['totals']['warnings'];
$this->log(count($files) . ' files were checked', Project::MSG_INFO);
if ($totalErrors > 0) {
$this->log($totalErrors . ' error' . ($totalErrors > 1 ? 's' : '') . ' detected', Project::MSG_ERR);
} else {
$this->log('No syntax errors detected', Project::MSG_INFO);
}
if ($totalWarnings > 0) {
$this->log($totalWarnings . ' warning' . ($totalWarnings > 1 ? 's' : '') . ' detected', Project::MSG_INFO);
}
}
/**
* Outputs the messages of a specific type for one file
* @param array $messages
* @param string $type
*/
protected function outputCustomFormatMessages($messages, $type) {
foreach ($messages as $line => $messagesPerLine) {
foreach ($messagesPerLine as $column => $messagesPerColumn) {
foreach ($messagesPerColumn as $message) {
$msgType = $message['type'];
if ($type == $msgType) {
$logLevel = Project::MSG_INFO;
if ($msgType == 'ERROR') {
$logLevel = Project::MSG_ERR;
} else if ($msgType == 'WARNING') {
$logLevel = Project::MSG_WARN;
}
$text = $message['message'];
$string = $msgType . ' in line ' . $line . ' column ' . $column . ': ' . $text;
$this->log($string, $logLevel);
}
}
}
}
}
} //end phpCodeSnifferTask
/**
* @package phing.tasks.ext
*/
class PhpCodeSnifferTask_FormatterElement extends DataType {
/**
* Type of output to generate
* @var string
*/
protected $type = "";
/**
* Output to file?
* @var bool
*/
protected $useFile = true;
/**
* Output file.
* @var string
*/
protected $outfile = "";
/**
* Validate config.
*/
public function parsingComplete () {
if(empty($this->type)) {
throw new BuildException("Format missing required 'type' attribute.");
}
if ($this->useFile && empty($this->outfile)) {
throw new BuildException("Format requires 'outfile' attribute when 'useFile' is true.");
}
}
public function setType ($type) {
$this->type = $type;
}
public function getType () {
return $this->type;
}
public function setUseFile ($useFile) {
$this->useFile = $useFile;
}
public function getUseFile () {
return $this->useFile;
}
public function setOutfile ($outfile) {
$this->outfile = $outfile;
}
public function getOutfile () {
return $this->outfile;
}
} //end FormatterElement
|