Skip to content

#121 Magento2.Templates.HelperInTemplate Rule porposal #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 16, 2019
25 changes: 25 additions & 0 deletions Magento2/Sniffs/Templates/HelperInTemplateSniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Rule: Do not use `helpers` in templates
## Background
The use of helpers is in general discouraged. 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.

Consider using ViewModel instead.

## How to fix

Typical example of a helper being used in a PHTML:
```html
<?php $_incl = $block->helper(<helper_class>)->...; ?>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In most cases it is $this->helper(<helper_class>), because $this refers to the template engine, not to the block.

```

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

```html
<?php $viewModel = $block->getViewModel(); ?>
```
or
```html
<?php $viewModel = $block->getData('viewModel'); ?>
```
48 changes: 48 additions & 0 deletions Magento2/Sniffs/Templates/HelperInTemplateSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Sniffs\Templates;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

/**
* Detects possible usage of helper in templates.
*/
class HelperInTemplateSniff implements Sniff
{
/**
* String representation of warning.
*
* @var string
*/
protected $warningMessage = 'Usage of helpers in templates is discouraged.';

/**
* Warning violation code.
*
* @var string
*/
protected $warningCode = 'FoundThis';

/**
* @inheritdoc
*/
public function register()
{
return [T_VARIABLE];
}

/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['content'] === 'helper(') {
$phpcsFile->addWarning($this->warningMessage, $stackPtr, $this->warningCode);
}
}
}