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