|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Space48\CodeQuality\Formatter; |
| 4 | + |
| 5 | +use Symfony\Component\Process\Process; |
| 6 | +use Symfony\Component\DomCrawler\Crawler; |
| 7 | + |
| 8 | +class PhpmdFormatter implements \GrumPHP\Formatter\ProcessFormatterInterface |
| 9 | +{ |
| 10 | + |
| 11 | + public function format(Process $process): string |
| 12 | + { |
| 13 | + $output = trim($process->getOutput()); |
| 14 | + if (!$output) { |
| 15 | + return $process->getErrorOutput(); |
| 16 | + } |
| 17 | + |
| 18 | + $xml = new Crawler($output); |
| 19 | + try { |
| 20 | + // will throw an exception if $output is not in expected format |
| 21 | + $xml->filter('file')->children(); |
| 22 | + } catch (\Exception $e) { |
| 23 | + return $output; |
| 24 | + } |
| 25 | + |
| 26 | + $formattedOutput = 'PHPMD. (To exclude rule add "@SuppressWarnings(PHPMD.RuleName)" to function or class phpdoc)' . "\n"; |
| 27 | + foreach ($xml->filter('file') as $node) { |
| 28 | + $name = $node->attributes->getNamedItem('name')->value; |
| 29 | + $formattedOutput .= sprintf("%'-". \strlen($name) . "s\n", '-'); |
| 30 | + $formattedOutput .= $name . "\n"; |
| 31 | + $formattedOutput .= sprintf("%'-". \strlen($name) . "s\n", '-'); |
| 32 | + |
| 33 | + foreach ($node->childNodes as $violation) { |
| 34 | + if ($violation->nodeName == '#text') { |
| 35 | + continue; |
| 36 | + } |
| 37 | + |
| 38 | + $formattedOutput .= sprintf( |
| 39 | + "% 11s | Line: % 3s | %s | %s\n", |
| 40 | + strtoupper($violation->nodeName), |
| 41 | + $violation->attributes->getNamedItem('beginline')->value, |
| 42 | + $violation->attributes->getNamedItem('rule')->value, |
| 43 | + trim($violation->textContent) |
| 44 | + ); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return $formattedOutput; |
| 49 | + } |
| 50 | +} |
0 commit comments