Skip to content

Commit 81cea42

Browse files
authored
Merge pull request #625 from PHPCSStandards/feature/524-common-getsniffcode-abstractsniffclass
Runner::processFile()/error handling: add more defensive coding
2 parents 36d731e + 53306fa commit 81cea42

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/Runner.php

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
namespace PHP_CodeSniffer;
1414

1515
use Exception;
16+
use InvalidArgumentException;
1617
use PHP_CodeSniffer\Exceptions\DeepExitException;
1718
use PHP_CodeSniffer\Exceptions\RuntimeException;
1819
use PHP_CodeSniffer\Files\DummyFile;
@@ -688,16 +689,23 @@ public function processFile($file)
688689
}
689690

690691
if (empty($sniffStack) === false) {
691-
if (empty($nextStack) === false
692-
&& isset($nextStack['class']) === true
693-
&& substr($nextStack['class'], -5) === 'Sniff'
694-
) {
695-
$sniffCode = Common::getSniffCode($nextStack['class']);
696-
} else {
692+
$sniffCode = '';
693+
try {
694+
if (empty($nextStack) === false
695+
&& isset($nextStack['class']) === true
696+
&& substr($nextStack['class'], -5) === 'Sniff'
697+
) {
698+
$sniffCode = 'the '.Common::getSniffCode($nextStack['class']).' sniff';
699+
}
700+
} catch (InvalidArgumentException $e) {
701+
// Sniff code could not be determined. This may be an abstract sniff class.
702+
}
703+
704+
if ($sniffCode === '') {
697705
$sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
698706
}
699707

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

703711
$file->addErrorOnLine($error, 1, 'Internal.Exception');

tests/Core/Util/Common/GetSniffCodeTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ public static function dataGetSniffCodeThrowsExceptionOnInputWhichIsNotASniffTes
108108
'Unqualified class name' => ['ClassName'],
109109
'Fully qualified class name, not enough parts' => ['Fully\\Qualified\\ClassName'],
110110
'Fully qualified class name, doesn\'t end on Sniff or UnitTest' => ['Fully\\Sniffs\\Qualified\\ClassName'],
111+
'Fully qualified class name, ends on Sniff, but isn\'t' => ['Fully\\Sniffs\\AbstractSomethingSniff'],
111112
];
112113

113114
}//end dataGetSniffCodeThrowsExceptionOnInputWhichIsNotASniffTestClass()

0 commit comments

Comments
 (0)