Skip to content

Commit

Permalink
Merge pull request #625 from PHPCSStandards/feature/524-common-getsni…
Browse files Browse the repository at this point in the history
…ffcode-abstractsniffclass

Runner::processFile()/error handling: add more defensive coding
  • Loading branch information
jrfnl authored Oct 7, 2024
2 parents 36d731e + 53306fa commit 81cea42
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/Runner.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
namespace PHP_CodeSniffer;

use Exception;
use InvalidArgumentException;
use PHP_CodeSniffer\Exceptions\DeepExitException;
use PHP_CodeSniffer\Exceptions\RuntimeException;
use PHP_CodeSniffer\Files\DummyFile;
Expand Down Expand Up @@ -688,16 +689,23 @@ public function processFile($file)
}

if (empty($sniffStack) === false) {
if (empty($nextStack) === false
&& isset($nextStack['class']) === true
&& substr($nextStack['class'], -5) === 'Sniff'
) {
$sniffCode = Common::getSniffCode($nextStack['class']);
} else {
$sniffCode = '';
try {
if (empty($nextStack) === false
&& isset($nextStack['class']) === true
&& substr($nextStack['class'], -5) === 'Sniff'
) {
$sniffCode = 'the '.Common::getSniffCode($nextStack['class']).' sniff';
}
} catch (InvalidArgumentException $e) {
// Sniff code could not be determined. This may be an abstract sniff class.
}

if ($sniffCode === '') {
$sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
}

$error .= sprintf(PHP_EOL.'The error originated in the %s sniff on line %s.', $sniffCode, $sniffStack['line']);
$error .= sprintf(PHP_EOL.'The error originated in %s on line %s.', $sniffCode, $sniffStack['line']);
}

$file->addErrorOnLine($error, 1, 'Internal.Exception');
Expand Down
1 change: 1 addition & 0 deletions tests/Core/Util/Common/GetSniffCodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ public static function dataGetSniffCodeThrowsExceptionOnInputWhichIsNotASniffTes
'Unqualified class name' => ['ClassName'],
'Fully qualified class name, not enough parts' => ['Fully\\Qualified\\ClassName'],
'Fully qualified class name, doesn\'t end on Sniff or UnitTest' => ['Fully\\Sniffs\\Qualified\\ClassName'],
'Fully qualified class name, ends on Sniff, but isn\'t' => ['Fully\\Sniffs\\AbstractSomethingSniff'],
];

}//end dataGetSniffCodeThrowsExceptionOnInputWhichIsNotASniffTestClass()
Expand Down

0 comments on commit 81cea42

Please sign in to comment.