From 810fe02f245c21823d4267e5f918064f70169fb4 Mon Sep 17 00:00:00 2001
From: Dan Wallis <mrdanwallis@gmail.com>
Date: Thu, 7 Jul 2022 12:13:49 +0100
Subject: [PATCH] Only auto-fix `$this` to `$block` when safe to do

---
 Magento2/Sniffs/Templates/ThisInTemplateSniff.php         | 5 +++--
 Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed | 2 +-
 Magento2/Tests/Templates/ThisInTemplateUnitTest.php       | 2 +-
 3 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/Magento2/Sniffs/Templates/ThisInTemplateSniff.php b/Magento2/Sniffs/Templates/ThisInTemplateSniff.php
index 74c27a6e..2aee085f 100644
--- a/Magento2/Sniffs/Templates/ThisInTemplateSniff.php
+++ b/Magento2/Sniffs/Templates/ThisInTemplateSniff.php
@@ -32,11 +32,12 @@ public function process(File $phpcsFile, $stackPtr)
         if ($phpcsFile->getTokensAsString($stackPtr, 1) !== '$this') {
             return;
         }
+
         $isHelperCall = $phpcsFile->findNext(T_STRING, $stackPtr, null, false, 'helper', true);
+
         if ($isHelperCall) {
             $phpcsFile->addWarning(self::MESSAGE_HELPER, $stackPtr, 'FoundHelper');
-        }
-        if ($phpcsFile->addFixableWarning(self::MESSAGE_THIS, $stackPtr, 'FoundThis') === true) {
+        } elseif ($phpcsFile->addFixableWarning(self::MESSAGE_THIS, $stackPtr, 'FoundThis') === true) {
             $phpcsFile->fixer->beginChangeset();
             $phpcsFile->fixer->replaceToken($stackPtr, '$block');
             $phpcsFile->fixer->endChangeset();
diff --git a/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed b/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed
index 04e0ae31..e865356b 100644
--- a/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed
+++ b/Magento2/Tests/Templates/ThisInTemplateUnitTest.inc.fixed
@@ -2,4 +2,4 @@
 echo $block->escapeHtml($block->getGroupCode());
 echo $block->escapeHtml($block->getGroupCode());
 $block->foo();
-$block->helper();
+$this->helper();
diff --git a/Magento2/Tests/Templates/ThisInTemplateUnitTest.php b/Magento2/Tests/Templates/ThisInTemplateUnitTest.php
index d2bed803..96d8661f 100644
--- a/Magento2/Tests/Templates/ThisInTemplateUnitTest.php
+++ b/Magento2/Tests/Templates/ThisInTemplateUnitTest.php
@@ -25,7 +25,7 @@ public function getWarningList()
         return [
             3 => 2,
             4 => 1,
-            5 => 2,
+            5 => 1,
         ];
     }
 }