diff --git a/Magento2/Sniffs/Templates/ThisInTemplateSniff.md b/Magento2/Sniffs/Templates/ThisInTemplateSniff.md index 071fada6..4b9284d4 100644 --- a/Magento2/Sniffs/Templates/ThisInTemplateSniff.md +++ b/Magento2/Sniffs/Templates/ThisInTemplateSniff.md @@ -14,6 +14,10 @@ Replace `$this` with `$block`. If you use private or protected methods, make the --- +# Rule: Do not use `helpers` in templates +## Background +The use of helpers is in general discouraged. For template files, consider using a ViewModel instead. + ## Reasoning The use of helpers is in general discouraged therefore any `$this->helper(<helper_class>)` code used in PHTML templates should be refactored. @@ -23,7 +27,7 @@ Consider using ViewModel instead. Typical example of a helper being used in a PHTML: ```html -<?php $_incl = $block->helper(<helper_class>)->...; ?> +<?php $_incl = $this->helper(<helper_class>)->...; ?> ``` Once the ViewModel is created, call it in the PHTML as follow: diff --git a/Magento2/Sniffs/Templates/ThisInTemplateSniff.php b/Magento2/Sniffs/Templates/ThisInTemplateSniff.php index be3ec293..95279236 100644 --- a/Magento2/Sniffs/Templates/ThisInTemplateSniff.php +++ b/Magento2/Sniffs/Templates/ThisInTemplateSniff.php @@ -13,19 +13,33 @@ */ class ThisInTemplateSniff implements Sniff { + /** + * Warning violation code. + * + * @var string + */ + protected $warningCodeFoundHelper = 'FoundHelper'; + /** * String representation of warning. * * @var string */ - protected $warningMessage = 'Usage of $this in template files is deprecated.'; + protected $warningMessageFoundHelper = 'The use of helpers in templates is discouraged. Use ViewModel instead.'; /** * Warning violation code. * * @var string */ - protected $warningCode = 'FoundThis'; + protected $warningCodeFoundThis = 'FoundThis'; + + /** + * String representation of warning. + * + * @var string + */ + protected $warningMessageFoundThis = 'The use of $this in templates is deprecated. Use $block instead.'; /** * @inheritdoc @@ -42,7 +56,12 @@ public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ($tokens[$stackPtr]['content'] === '$this') { - $phpcsFile->addWarning($this->warningMessage, $stackPtr, $this->warningCode); + $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); + } } } }