-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathUseSprintfInExceptionsSniff.php
74 lines (56 loc) · 1.91 KB
/
UseSprintfInExceptionsSniff.php
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
<?php
declare(strict_types=1);
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao\EasyCodingStandard\Sniffs;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\TokenHelper;
final class UseSprintfInExceptionsSniff implements Sniff
{
public function register(): array
{
return [T_THROW];
}
public function process(File $phpcsFile, $stackPtr): void
{
$tokens = $phpcsFile->getTokens();
if (T_THROW !== $tokens[$stackPtr]['code']) {
return;
}
$next = $this->getNextNonWhitespaceToken($tokens, $stackPtr);
// We are not dealing with "throw new"
if (T_NEW !== $tokens[$next]['code']) {
return;
}
$next = TokenHelper::findNext($phpcsFile, T_STRING, $next);
// We are not dealing with an exception class
if (!str_ends_with((string) $tokens[$next]['content'], 'Exception')) {
return;
}
$next = $this->getNextNonWhitespaceToken($tokens, $next);
// There is no opening parenthesis after the class name
if (T_OPEN_PARENTHESIS !== $tokens[$next]['code']) {
return;
}
$next = $this->getNextNonWhitespaceToken($tokens, $next);
// A non-interpolated string will have the T_CONSTANT_ENCAPSED_STRING code, so it
// is enough to check for T_DOUBLE_QUOTED_STRING here
if (T_DOUBLE_QUOTED_STRING !== $tokens[$next]['code']) {
return;
}
$phpcsFile->addError('Using string interpolation in exception messages is not allowed. Use sprintf() instead.', $stackPtr, self::class);
}
private function getNextNonWhitespaceToken(array $tokens, int $index): int
{
do {
++$index;
} while (T_WHITESPACE === $tokens[$index]['code']);
return $index;
}
}