Skip to content

Commit 9ea4f74

Browse files
committed
magento#121 Magento2.Templates.HelperInTemplate Rule porposal
1 parent d2f07a9 commit 9ea4f74

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Rule: Do not use `helpers` in templates
2+
## Background
3+
The use of helpers is in general discouraged. Consider using a ViewModel instead.
4+
5+
## Reasoning
6+
The use of helpers is in general discouraged therefore any `$this->helper(<helper_class>)` code used in PHTML templates should be refactored.
7+
8+
Consider using ViewModel instead.
9+
10+
## How to fix
11+
12+
Typical example of a helper being used in a PHTML:
13+
```html
14+
<?php $_incl = $block->helper(<helper_class>)->...; ?>
15+
```
16+
17+
Once the ViewModel is created, call it in the PHTML as follow:
18+
19+
```html
20+
<?php $viewModel = $block->getViewModel(); ?>
21+
```
22+
or
23+
```html
24+
<?php $viewModel = $block->getData('viewModel'); ?>
25+
```
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
/**
3+
* Copyright © Magento. All rights reserved.
4+
* See COPYING.txt for license details.
5+
*/
6+
namespace Magento2\Sniffs\Templates;
7+
8+
use PHP_CodeSniffer\Sniffs\Sniff;
9+
use PHP_CodeSniffer\Files\File;
10+
11+
/**
12+
* Detects possible usage of helper in templates.
13+
*/
14+
class HelperInTemplateSniff implements Sniff
15+
{
16+
/**
17+
* String representation of warning.
18+
*
19+
* @var string
20+
*/
21+
protected $warningMessage = 'Usage of helpers in templates is discouraged.';
22+
23+
/**
24+
* Warning violation code.
25+
*
26+
* @var string
27+
*/
28+
protected $warningCode = 'FoundThis';
29+
30+
/**
31+
* @inheritdoc
32+
*/
33+
public function register()
34+
{
35+
return [T_VARIABLE];
36+
}
37+
38+
/**
39+
* @inheritdoc
40+
*/
41+
public function process(File $phpcsFile, $stackPtr)
42+
{
43+
$tokens = $phpcsFile->getTokens();
44+
if ($tokens[$stackPtr]['content'] === 'helper(') {
45+
$phpcsFile->addWarning($this->warningMessage, $stackPtr, $this->warningCode);
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)