Skip to content
Merged
6 changes: 5 additions & 1 deletion Magento2/Sniffs/Templates/ThisInTemplateSniff.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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:
Expand Down
25 changes: 22 additions & 3 deletions Magento2/Sniffs/Templates/ThisInTemplateSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}
}
}
}