1313 */
1414class ThisInTemplateSniff implements Sniff
1515{
16- /**
17- * Warning violation code.
18- *
19- * @var string
20- */
21- protected $ warningCodeFoundHelper = 'FoundHelper ' ;
22-
23- /**
24- * String representation of warning.
25- *
26- * @var string
27- */
28- protected $ warningMessageFoundHelper = 'The use of helpers in templates is discouraged. Use ViewModel instead. ' ;
29-
30- /**
31- * Warning violation code.
32- *
33- * @var string
34- */
35- protected $ warningCodeFoundThis = 'FoundThis ' ;
36-
37- /**
38- * String representation of warning.
39- *
40- * @var string
41- */
42- protected $ warningMessageFoundThis = 'The use of $this in templates is deprecated. Use $block instead. ' ;
16+ private const MESSAGE_THIS = 'The use of $this in templates is deprecated. Use $block instead. ' ;
17+ private const MESSAGE_HELPER = 'The use of helpers in templates is discouraged. Use ViewModel instead. ' ;
4318
4419 /**
4520 * @inheritdoc
@@ -54,14 +29,17 @@ public function register()
5429 */
5530 public function process (File $ phpcsFile , $ stackPtr )
5631 {
57- $ tokens = $ phpcsFile ->getTokens ();
58- if ($ tokens [$ stackPtr ]['content ' ] === '$this ' ) {
59- $ position = $ phpcsFile ->findNext (T_STRING , $ stackPtr , null , false , 'helper ' , true );
60- if ($ position !== false ) {
61- $ phpcsFile ->addWarning ($ this ->warningMessageFoundHelper , $ position , $ this ->warningCodeFoundHelper );
62- } else {
63- $ phpcsFile ->addWarning ($ this ->warningMessageFoundThis , $ stackPtr , $ this ->warningCodeFoundThis );
64- }
32+ if ($ phpcsFile ->getTokensAsString ($ stackPtr , 1 ) !== '$this ' ) {
33+ return ;
34+ }
35+ $ isHelperCall = $ phpcsFile ->findNext (T_STRING , $ stackPtr , null , false , 'helper ' , true );
36+ if ($ isHelperCall ) {
37+ $ phpcsFile ->addWarning (self ::MESSAGE_HELPER , $ stackPtr , 'FoundHelper ' );
38+ }
39+ if ($ phpcsFile ->addFixableWarning (self ::MESSAGE_THIS , $ stackPtr , 'FoundThis ' ) === true ) {
40+ $ phpcsFile ->fixer ->beginChangeset ();
41+ $ phpcsFile ->fixer ->replaceToken ($ stackPtr , '$block ' );
42+ $ phpcsFile ->fixer ->endChangeset ();
6543 }
6644 }
6745}
0 commit comments