1010use PHP_CodeSniffer \Files \File ;
1111
1212/**
13- * Detects no try block detected when processing system resources
13+ * Detects missing try-catch block when processing system resources.
1414 */
1515class TryProcessSystemResourcesSniff implements Sniff
1616{
@@ -19,17 +19,17 @@ class TryProcessSystemResourcesSniff implements Sniff
1919 *
2020 * @var string
2121 */
22- protected $ warningMessage = 'The code MUST be wrapped with a try block if the method uses system resources . ' ;
22+ protected $ warningMessage = 'The code must be wrapped with a try block if the method uses system resources. ' ;
2323
2424 /**
2525 * Warning violation code.
2626 *
2727 * @var string
2828 */
29- protected $ warningCode = ' TryProcessSystem ' ;
29+ protected $ warningCode = 'MissingTryCatch ' ;
3030
3131 /**
32- * Searched functions.
32+ * Search for functions that start with .
3333 *
3434 * @var array
3535 */
@@ -51,41 +51,29 @@ public function register()
5151 */
5252 public function process (File $ phpcsFile , $ stackPtr )
5353 {
54- $ isSystemResource = false ;
55-
5654 $ tokens = $ phpcsFile ->getTokens ();
57- $ match = $ tokens [$ stackPtr ]['content ' ];
5855
5956 foreach ($ this ->functions as $ function ) {
60- if (strpos ($ match , $ function ) === false ) {
57+ if (strpos ($ tokens [ $ stackPtr ][ ' content ' ] , $ function ) !== 0 ) {
6158 continue ;
6259 }
60+ $ tryPosition = $ phpcsFile ->findPrevious (T_TRY , $ stackPtr - 1 );
6361
64- $ isSystemResource = true ;
65- break ;
66- }
67-
68- if (false === $ isSystemResource ) {
69- // Probably no a system resource no check
70- return ;
71- }
72-
73- $ tryPosition = $ phpcsFile ->findPrevious (T_TRY , $ stackPtr - 1 );
74-
75- if ($ tryPosition !== false ) {
76- $ tryTag = $ tokens [$ tryPosition ];
77- $ start = $ tryTag ['scope_opener ' ];
78- $ end = $ tryTag ['scope_closer ' ];
79- if ($ stackPtr > $ start && $ stackPtr < $ end ) {
80- // element is warped by try no check required
81- return ;
62+ if ($ tryPosition !== false ) {
63+ $ tryTag = $ tokens [$ tryPosition ];
64+ $ start = $ tryTag ['scope_opener ' ];
65+ $ end = $ tryTag ['scope_closer ' ];
66+ if ($ stackPtr > $ start && $ stackPtr < $ end ) {
67+ // element is warped by try no check required
68+ return ;
69+ }
8270 }
83- }
8471
85- $ phpcsFile ->addWarning (
86- $ this ->warningMessage ,
87- $ stackPtr ,
88- $ this ->warningCode
89- );
72+ $ phpcsFile ->addWarning (
73+ $ this ->warningMessage ,
74+ $ stackPtr ,
75+ $ this ->warningCode
76+ );
77+ }
9078 }
9179}
0 commit comments