@@ -44,19 +44,29 @@ public function process(File $phpcsFile, $stackPtr)
44
44
$ tokens = $ phpcsFile ->getTokens ();
45
45
$ endOfStatement = $ phpcsFile ->findEndOfStatement ($ stackPtr );
46
46
$ posOfException = $ phpcsFile ->findNext (T_STRING , $ stackPtr , $ endOfStatement );
47
- $ content = $ tokens [$ posOfException ]['content ' ];
48
- $ exceptionClassInUseStatement = false ;
47
+
48
+ $ fullExceptionString = $ this ->getFullClassNameAndAlias ($ tokens , $ stackPtr , $ endOfStatement );
49
+ $ exceptionString = 'Exception ' ;
50
+ $ customExceptionFound = false ;
49
51
foreach ($ tokens as $ key => $ token ) {
50
52
if ($ token ['code ' ] === T_USE ) {
51
53
$ endOfUse = $ phpcsFile ->findEndOfStatement ($ key );
52
- $ posOfException = $ phpcsFile ->findNext (T_STRING , $ key , $ key + 3 , false , 'Exception ' );
53
- if ($ posOfException && $ phpcsFile ->findNext (T_SEMICOLON , $ posOfException +1 , $ endOfUse + 1 )) {
54
- $ exceptionClassInUseStatement = true ;
55
- break ;
54
+ $ useStatementValue = $ this ->getFullClassNameAndAlias ($ tokens , $ key , $ endOfUse );
55
+ //we safely consider use statement has alias will not be a direct exception class
56
+ if (empty ($ useStatementValue ['alias ' ])) {
57
+ if (substr ($ useStatementValue ['name ' ], 0 , strlen ($ exceptionString )) !== $ exceptionString
58
+ && substr ($ useStatementValue ['name ' ], -strlen ($ exceptionString )) === $ exceptionString
59
+ && $ useStatementValue ['name ' ] !== $ exceptionString
60
+ ) {
61
+ $ customExceptionFound = true ;
62
+ break ;
63
+ }
56
64
}
57
65
}
58
66
}
59
- if ($ content === '\Exception ' || ($ content === 'Exception ' && $ exceptionClassInUseStatement )) {
67
+ if (($ tokens [$ posOfException ]['content ' ] === 'Exception ' && !$ customExceptionFound )
68
+ || $ fullExceptionString ['name ' ] === '\Exception '
69
+ ) {
60
70
$ phpcsFile ->addWarning (
61
71
$ this ->warningMessage ,
62
72
$ stackPtr ,
@@ -65,4 +75,33 @@ public function process(File $phpcsFile, $stackPtr)
65
75
);
66
76
}
67
77
}
78
+
79
+ /**
80
+ * Get full class name and alias
81
+ *
82
+ * @param array $tokens
83
+ * @param int $start
84
+ * @param int $end
85
+ * @return array
86
+ */
87
+ private function getFullClassNameAndAlias ($ tokens , $ start , $ end )
88
+ {
89
+ $ fullName = $ alias = '' ;
90
+ $ foundAlias = false ;
91
+ for ($ i = $ start ; $ i <= $ end ; $ i ++) {
92
+ $ type = $ tokens [$ i ]['code ' ];
93
+ if ($ type === T_AS ) {
94
+ $ foundAlias = true ;
95
+ continue ;
96
+ }
97
+ if ($ type === T_STRING || $ type === T_NS_SEPARATOR ) {
98
+ if (!$ foundAlias ) {
99
+ $ fullName .= $ tokens [$ i ]['content ' ];
100
+ } else {
101
+ $ alias = $ tokens [$ i ]['content ' ];
102
+ }
103
+ }
104
+ }
105
+ return ['name ' => $ fullName , 'alias ' => $ alias ];
106
+ }
68
107
}
0 commit comments