diff --git a/Magento2/Sniffs/Templates/ThisInTemplateSniff.php b/Magento2/Sniffs/Templates/ThisInTemplateSniff.php index 9b5e5358..74c27a6e 100644 --- a/Magento2/Sniffs/Templates/ThisInTemplateSniff.php +++ b/Magento2/Sniffs/Templates/ThisInTemplateSniff.php @@ -13,33 +13,8 @@ */ class ThisInTemplateSniff implements Sniff { - /** - * Warning violation code. - * - * @var string - */ - protected $warningCodeFoundHelper = 'FoundHelper'; - - /** - * String representation of warning. - * - * @var string - */ - protected $warningMessageFoundHelper = 'The use of helpers in templates is discouraged. Use ViewModel instead.'; - - /** - * Warning violation code. - * - * @var string - */ - protected $warningCodeFoundThis = 'FoundThis'; - - /** - * String representation of warning. - * - * @var string - */ - protected $warningMessageFoundThis = 'The use of $this in templates is deprecated. Use $block instead.'; + private const MESSAGE_THIS = 'The use of $this in templates is deprecated. Use $block instead.'; + private const MESSAGE_HELPER = 'The use of helpers in templates is discouraged. Use ViewModel instead.'; /** * @inheritdoc @@ -54,14 +29,17 @@ public function register() */ public function process(File $phpcsFile, $stackPtr) { - $tokens = $phpcsFile->getTokens(); - if ($tokens[$stackPtr]['content'] === '$this') { - $position = $phpcsFile->findNext(T_STRING, $stackPtr, null, false, 'helper', true); - if ($position !== false) { - $phpcsFile->addWarning($this->warningMessageFoundHelper, $position, $this->warningCodeFoundHelper); - } else { - $phpcsFile->addWarning($this->warningMessageFoundThis, $stackPtr, $this->warningCodeFoundThis); - } + if ($phpcsFile->getTokensAsString($stackPtr, 1) !== '$this') { + return; + } + $isHelperCall = $phpcsFile->findNext(T_STRING, $stackPtr, null, false, 'helper', true); + if ($isHelperCall) { + $phpcsFile->addWarning(self::MESSAGE_HELPER, $stackPtr, 'FoundHelper'); + } + if ($phpcsFile->addFixableWarning(self::MESSAGE_THIS, $stackPtr, 'FoundThis') === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($stackPtr, '$block'); + $phpcsFile->fixer->endChangeset(); } } } diff --git a/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed b/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed new file mode 100644 index 00000000..04e0ae31 --- /dev/null +++ b/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed @@ -0,0 +1,5 @@ +escapeHtml($block->getGroupCode()); +echo $block->escapeHtml($block->getGroupCode()); +$block->foo(); +$block->helper(); diff --git a/Magento2/Tests/Templates/ThisInTemplateUnitTest.php b/Magento2/Tests/Templates/ThisInTemplateUnitTest.php index 96d8661f..d2bed803 100644 --- a/Magento2/Tests/Templates/ThisInTemplateUnitTest.php +++ b/Magento2/Tests/Templates/ThisInTemplateUnitTest.php @@ -25,7 +25,7 @@ public function getWarningList() return [ 3 => 2, 4 => 1, - 5 => 1, + 5 => 2, ]; } }