-
Notifications
You must be signed in to change notification settings - Fork 3
/
ExceptionSuffixSniff.php
48 lines (37 loc) · 1.24 KB
/
ExceptionSuffixSniff.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
<?php
namespace Worksome\CodingStyle\Sniffs\Classes;
use Illuminate\Support\Str;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
class ExceptionSuffixSniff implements Sniff
{
public string $suffix = 'Exception';
public function register(): array
{
return [
T_EXTENDS,
];
}
public function process(File $phpcsFile, $stackPtr)
{
$baseClassNameLength = 0;
while (Str::endsWith($phpcsFile->getTokensAsString($stackPtr + 2, $baseClassNameLength + 1), '\\')) {
$baseClassNameLength += 2;
}
$baseClassName = $phpcsFile->getTokensAsString($stackPtr + 2, max($baseClassNameLength, 1));
if (! Str::endsWith($baseClassName, $this->suffix) || ! Str::contains($baseClassName, 'Exception')) {
return;
}
$classNamePointer = $stackPtr - 2;
$className = $phpcsFile->getTokensAsString($classNamePointer, 1);
// Check if class is named with Exceptions suffix.
if (Str::endsWith($className, $this->suffix)) {
return;
}
$phpcsFile->addError(
'Exceptions should have `Exception` suffix.',
$classNamePointer,
self::class,
);
}
}