Skip to content

Commit 1bdb24d

Browse files
authored
Merge pull request #122 from diazwatson/121_HelperInTemplateRule
#121 Magento2.Templates.HelperInTemplate Rule porposal
2 parents fefba0a + 5182dca commit 1bdb24d

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

Magento2/Sniffs/Templates/ThisInTemplateSniff.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ Replace `$this` with `$block`. If you use private or protected methods, make the
1414

1515
---
1616

17+
# Rule: Do not use `helpers` in templates
18+
## Background
19+
The use of helpers is in general discouraged. For template files, consider using a ViewModel instead.
20+
1721
## Reasoning
1822
The use of helpers is in general discouraged therefore any `$this->helper(<helper_class>)` code used in PHTML templates should be refactored.
1923

@@ -23,7 +27,7 @@ Consider using ViewModel instead.
2327

2428
Typical example of a helper being used in a PHTML:
2529
```html
26-
<?php $_incl = $block->helper(<helper_class>)->...; ?>
30+
<?php $_incl = $this->helper(<helper_class>)->...; ?>
2731
```
2832

2933
Once the ViewModel is created, call it in the PHTML as follow:

Magento2/Sniffs/Templates/ThisInTemplateSniff.php

+22-3
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,33 @@
1313
*/
1414
class ThisInTemplateSniff implements Sniff
1515
{
16+
/**
17+
* Warning violation code.
18+
*
19+
* @var string
20+
*/
21+
protected $warningCodeFoundHelper = 'FoundHelper';
22+
1623
/**
1724
* String representation of warning.
1825
*
1926
* @var string
2027
*/
21-
protected $warningMessage = 'Usage of $this in template files is deprecated.';
28+
protected $warningMessageFoundHelper = 'The use of helpers in templates is discouraged. Use ViewModel instead.';
2229

2330
/**
2431
* Warning violation code.
2532
*
2633
* @var string
2734
*/
28-
protected $warningCode = 'FoundThis';
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.';
2943

3044
/**
3145
* @inheritdoc
@@ -42,7 +56,12 @@ public function process(File $phpcsFile, $stackPtr)
4256
{
4357
$tokens = $phpcsFile->getTokens();
4458
if ($tokens[$stackPtr]['content'] === '$this') {
45-
$phpcsFile->addWarning($this->warningMessage, $stackPtr, $this->warningCode);
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+
}
4665
}
4766
}
4867
}

0 commit comments

Comments
 (0)