Skip to content

Commit 89c8442

Browse files
committed
AC-2221: Autofix for ThisInTemplate Sniff
1 parent 81ebc1d commit 89c8442

File tree

3 files changed

+19
-36
lines changed

3 files changed

+19
-36
lines changed

Magento2/Sniffs/Templates/ThisInTemplateSniff.php

+13-35
Original file line numberDiff line numberDiff line change
@@ -13,33 +13,8 @@
1313
*/
1414
class ThisInTemplateSniff implements Sniff
1515
{
16-
/**
17-
* Warning violation code.
18-
*
19-
* @var string
20-
*/
21-
protected $warningCodeFoundHelper = 'FoundHelper';
22-
23-
/**
24-
* String representation of warning.
25-
*
26-
* @var string
27-
*/
28-
protected $warningMessageFoundHelper = 'The use of helpers in templates is discouraged. Use ViewModel instead.';
29-
30-
/**
31-
* Warning violation code.
32-
*
33-
* @var string
34-
*/
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.';
16+
private const MESSAGE_THIS = 'The use of $this in templates is deprecated. Use $block instead.';
17+
private const MESSAGE_HELPER = 'The use of helpers in templates is discouraged. Use ViewModel instead.';
4318

4419
/**
4520
* @inheritdoc
@@ -54,14 +29,17 @@ public function register()
5429
*/
5530
public function process(File $phpcsFile, $stackPtr)
5631
{
57-
$tokens = $phpcsFile->getTokens();
58-
if ($tokens[$stackPtr]['content'] === '$this') {
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-
}
32+
if ($phpcsFile->getTokensAsString($stackPtr, 1) !== '$this') {
33+
return;
34+
}
35+
$isHelperCall = $phpcsFile->findNext(T_STRING, $stackPtr, null, false, 'helper', true);
36+
if ($isHelperCall) {
37+
$phpcsFile->addWarning(self::MESSAGE_HELPER, $stackPtr, 'FoundHelper');
38+
}
39+
if ($phpcsFile->addFixableWarning(self::MESSAGE_THIS, $stackPtr, 'FoundThis') === true) {
40+
$phpcsFile->fixer->beginChangeset();
41+
$phpcsFile->fixer->replaceToken($stackPtr, '$block');
42+
$phpcsFile->fixer->endChangeset();
6543
}
6644
}
6745
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
echo $block->escapeHtml($block->getGroupCode());
3+
echo $block->escapeHtml($block->getGroupCode());
4+
$block->foo();
5+
$block->helper();

Magento2/Tests/Templates/ThisInTemplateUnitTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public function getWarningList()
2525
return [
2626
3 => 2,
2727
4 => 1,
28-
5 => 1,
28+
5 => 2,
2929
];
3030
}
3131
}

0 commit comments

Comments
 (0)