From e881f5774c4124b7d4af30a95ce679996a8fac92 Mon Sep 17 00:00:00 2001
From: Senthil Kumar Muppidathi <senthilengg@users.noreply.github.com>
Date: Tue, 14 Jan 2025 15:12:25 +0700
Subject: [PATCH 1/9] Fix for issue #39530 to avoid regenerating admin grid
 flat table

Updating indexer state hash upon creation of new encryption key from admin
---
 .../Model/ResourceModel/Key/Change.php        | 62 +++++++++++++++++++
 1 file changed, 62 insertions(+)

diff --git a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
index 0d916389af994..7037ae967b88c 100644
--- a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
+++ b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
@@ -14,6 +14,7 @@
 use Magento\Framework\Config\Data\ConfigData;
 use Magento\Framework\Config\File\ConfigFilePool;
 use Magento\Framework\Encryption\EncryptorInterface;
+use Magento\Framework\Encryption\Encryptor;
 use Magento\Framework\Exception\FileSystemException;
 use Magento\Framework\Exception\LocalizedException;
 use Magento\Framework\Filesystem;
@@ -21,6 +22,9 @@
 use Magento\Framework\Math\Random;
 use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
 use Magento\Framework\Model\ResourceModel\Db\Context;
+use Magento\Framework\Indexer\ConfigInterface;
+use Magento\Framework\Json\EncoderInterface;
+use Magento\Indexer\Model\ResourceModel\Indexer\State\CollectionFactory;
 
 /**
  * Encryption key changer resource model
@@ -71,6 +75,27 @@ class Change extends AbstractDb
      */
     protected $random;
 
+    /**
+     * Indexer Config
+     *
+     * @var IndexerConfig
+     */
+    protected $indexerConfig;
+
+    /**
+     * Json Encoder
+     *
+     * @var Encoder
+     */
+    protected $encoder;
+
+    /**
+     * Indexer State Collection Factory
+     *
+     * @var IndexerStateCollection
+     */
+    protected $indexerStateCollection;
+
     /**
      * @param Context $context
      * @param Filesystem $filesystem
@@ -78,6 +103,9 @@ class Change extends AbstractDb
      * @param EncryptorInterface $encryptor
      * @param Writer $writer
      * @param Random $random
+     * @param ConfigInterface $indexerConfig
+     * @param EncoderInterface $encoder
+     * @param CollectionFactory $indexerStateCollection
      * @param string $connectionName
      */
     public function __construct(
@@ -87,6 +115,9 @@ public function __construct(
         EncryptorInterface $encryptor,
         Writer $writer,
         Random $random,
+        ConfigInterface $indexerConfig,
+        EncoderInterface $encoder,
+        CollectionFactory $indexerStateCollection,
         $connectionName = null
     ) {
         $this->encryptor = clone $encryptor;
@@ -95,6 +126,9 @@ public function __construct(
         $this->structure = $structure;
         $this->writer = $writer;
         $this->random = $random;
+        $this->indexerConfig = $indexerConfig;
+        $this->encoder = $encoder;
+        $this->indexerStateCollection = $indexerStateCollection;
     }
 
     /**
@@ -139,6 +173,7 @@ public function changeEncryptionKey($key = null)
         try {
             $this->_reEncryptSystemConfigurationValues();
             $this->_reEncryptCreditCardNumbers();
+            $this->_updateIndexersHash();
             $this->writer->saveConfig($configData);
             $this->commit();
             return $key;
@@ -207,4 +242,31 @@ protected function _reEncryptCreditCardNumbers()
             );
         }
     }
+
+    /**
+     * Retrieve indexer state and update the hash with new encryption key
+     *
+     * @return void
+     */
+    protected function _updateIndexersHash(){
+        
+        $stateIndexers = [];
+        $stateCollection = $this->indexerStateCollection->create();
+        foreach ($stateCollection->getItems() as $state) {
+            /** @var \Magento\Indexer\Model\Indexer\State $state */
+            $stateIndexers[$state->getIndexerId()] = $state;
+        }
+        
+        foreach ($this->indexerConfig->getIndexers() as $indexerId => $indexerConfig) {
+            $newHashConfig = $this->encryptor->hash(
+                $this->encoder->encode($indexerConfig),
+                Encryptor::HASH_VERSION_MD5
+            );
+
+            if (isset($stateIndexers[$indexerId])) {
+                $stateIndexers[$indexerId]->setHashConfig($newHashConfig);
+                $stateIndexers[$indexerId]->save();
+            }
+        }
+    }
 }

From ebbfbb1c975f2bf8ccd569562cd97556389b6c8d Mon Sep 17 00:00:00 2001
From: Senthil Kumar Muppidathi <senthilengg@users.noreply.github.com>
Date: Wed, 15 Jan 2025 10:57:21 +0700
Subject: [PATCH 2/9] Adding Dependency to the module.xml

Adding Indexer Dependency to make the static test build pass
---
 app/code/Magento/EncryptionKey/etc/module.xml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/app/code/Magento/EncryptionKey/etc/module.xml b/app/code/Magento/EncryptionKey/etc/module.xml
index 1a70ce0ddfb72..6ffada634b840 100644
--- a/app/code/Magento/EncryptionKey/etc/module.xml
+++ b/app/code/Magento/EncryptionKey/etc/module.xml
@@ -10,6 +10,7 @@
         <sequence>
             <module name="Magento_Customer"/>
             <module name="Magento_User"/>
+            <module name="Magento_Indexer"/>
         </sequence>
     </module>
 </config>

From be0ea8f2033001ab9472bad28da0a25f746806f3 Mon Sep 17 00:00:00 2001
From: Senthil Kumar Muppidathi <senthilengg@users.noreply.github.com>
Date: Wed, 15 Jan 2025 11:03:32 +0700
Subject: [PATCH 3/9] Fixing CodeSniff violation

---
 .../Magento/EncryptionKey/Model/ResourceModel/Key/Change.php | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
index 7037ae967b88c..4ce83884045b9 100644
--- a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
+++ b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
@@ -244,11 +244,12 @@ protected function _reEncryptCreditCardNumbers()
     }
 
     /**
-     * Retrieve indexer state and update the hash with new encryption key
+     * Refresh the indexer hash to avoid grid data regeneration
      *
      * @return void
      */
-    protected function _updateIndexersHash(){
+    protected function _updateIndexersHash()
+    {
         
         $stateIndexers = [];
         $stateCollection = $this->indexerStateCollection->create();

From b3090e50f17a033a5a57d405b5ffd506e009d767 Mon Sep 17 00:00:00 2001
From: Senthil Kumar Muppidathi <senthilengg@users.noreply.github.com>
Date: Wed, 15 Jan 2025 13:31:46 +0700
Subject: [PATCH 4/9] Updating dependency in composer.json

---
 app/code/Magento/EncryptionKey/composer.json | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/app/code/Magento/EncryptionKey/composer.json b/app/code/Magento/EncryptionKey/composer.json
index 804b7ac289e60..7e61119035fe1 100644
--- a/app/code/Magento/EncryptionKey/composer.json
+++ b/app/code/Magento/EncryptionKey/composer.json
@@ -8,7 +8,8 @@
         "php": "~8.2.0||~8.3.0||~8.4.0",
         "magento/framework": "*",
         "magento/module-backend": "*",
-        "magento/module-config": "*"
+        "magento/module-config": "*",
+        "magento/module-indexer": "*"
     },
     "type": "magento2-module",
     "license": [

From f51a23abb2939e42380507e70768cd79967cca22 Mon Sep 17 00:00:00 2001
From: Senthilkumar Muppidathi <senthil@Senthilkumars-MacBook-Pro.local>
Date: Wed, 15 Jan 2025 13:43:53 +0530
Subject: [PATCH 5/9] Fixing Unit test setup and removed indexer from module
 sequence

---
 .../Model/ResourceModel/Key/Change.php        |  2 ++
 .../Model/ResourceModel/Key/ChangeTest.php    | 26 ++++++++++++++++++-
 app/code/Magento/EncryptionKey/etc/module.xml |  1 -
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
index 4ce83884045b9..1ee317a9a143c 100644
--- a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
+++ b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
@@ -107,6 +107,8 @@ class Change extends AbstractDb
      * @param EncoderInterface $encoder
      * @param CollectionFactory $indexerStateCollection
      * @param string $connectionName
+     * 
+     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
      */
     public function __construct(
         Context $context,
diff --git a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
index b0c5ecdc8ce19..ab31ac45da692 100644
--- a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
+++ b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
@@ -22,6 +22,9 @@
 use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
 use PHPUnit\Framework\MockObject\MockObject;
 use PHPUnit\Framework\TestCase;
+use Magento\Framework\Indexer\ConfigInterface;
+use Magento\Framework\Json\EncoderInterface;
+use Magento\Indexer\Model\ResourceModel\Indexer\State\CollectionFactory;
 
 /**
  * Test Class For Magento\EncryptionKey\Model\ResourceModel\Key\Change
@@ -63,6 +66,15 @@ class ChangeTest extends TestCase
     /** @var Change */
     protected $model;
 
+    /** @var ConfigInterface|MockObject */
+    protected $indexerConfigMock;
+    
+    /** @var EncoderInterface|MockObject */
+    protected $encoderMock;
+
+    /** @var CollectionFactory|MockObject */
+    protected $indexerStateCollectionMock;
+
     protected function setUp(): void
     {
         $this->encryptMock = $this->getMockBuilder(EncryptorInterface::class)
@@ -98,6 +110,15 @@ protected function setUp(): void
             ->disableOriginalConstructor()
             ->getMock();
         $this->randomMock = $this->createMock(Random::class);
+        $this->indexerConfigMock = $this->getMockBuilder(ConfigInterface::class)
+            ->disableOriginalConstructor()
+            ->getMockForAbstractClass();
+        $this->encoderMock = $this->getMockBuilder(EncoderInterface::class)
+            ->disableOriginalConstructor()
+            ->getMockForAbstractClass();
+        $this->indexerStateCollectionMock = $this->getMockBuilder(CollectionFactory::class)
+            ->disableOriginalConstructor()
+            ->getMock();
 
         $helper = new ObjectManager($this);
 
@@ -112,7 +133,10 @@ protected function setUp(): void
                 'resource' => $this->resourceMock,
                 'transactionManager' => $this->transactionMock,
                 'relationProcessor' => $this->objRelationMock,
-                'random' => $this->randomMock
+                'random' => $this->randomMock,
+                'indexerConfig' => $this->indexerConfigMock,
+                'encoder' => $this->encoderMock,
+                'indexerStateCollection' => $this->indexerStateCollectionMock,
             ]
         );
     }
diff --git a/app/code/Magento/EncryptionKey/etc/module.xml b/app/code/Magento/EncryptionKey/etc/module.xml
index 6ffada634b840..1a70ce0ddfb72 100644
--- a/app/code/Magento/EncryptionKey/etc/module.xml
+++ b/app/code/Magento/EncryptionKey/etc/module.xml
@@ -10,7 +10,6 @@
         <sequence>
             <module name="Magento_Customer"/>
             <module name="Magento_User"/>
-            <module name="Magento_Indexer"/>
         </sequence>
     </module>
 </config>

From 52b508ad7d386b84f1b2ad95161e81567de07427 Mon Sep 17 00:00:00 2001
From: Senthilkumar Muppidathi <senthil@Senthilkumars-MacBook-Pro.local>
Date: Thu, 16 Jan 2025 11:47:33 +0530
Subject: [PATCH 6/9] Adding unit test and coding standard fixes

---
 .../Model/ResourceModel/Key/Change.php        | 52 ++++++++++---------
 .../Model/ResourceModel/Key/ChangeTest.php    |  2 +-
 2 files changed, 29 insertions(+), 25 deletions(-)

diff --git a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
index 1ee317a9a143c..b4bca5c03b6c3 100644
--- a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
+++ b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
@@ -33,9 +33,9 @@
  * @api
  *
  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
- * @since 100.0.2
+ * @since                                          100.0.2
  * @deprecated
- * @see Extensible Reencryption Mechanism
+ * @see                                            Extensible Reencryption Mechanism
  */
 class Change extends AbstractDb
 {
@@ -70,13 +70,13 @@ class Change extends AbstractDb
     /**
      * Random string generator
      *
-     * @var Random
+     * @var   Random
      * @since 100.0.4
      */
     protected $random;
 
     /**
-     * Indexer Config
+     * Indexer Configuration
      *
      * @var IndexerConfig
      */
@@ -97,17 +97,17 @@ class Change extends AbstractDb
     protected $indexerStateCollection;
 
     /**
-     * @param Context $context
-     * @param Filesystem $filesystem
-     * @param Structure $structure
+     * @param Context            $context
+     * @param Filesystem         $filesystem
+     * @param Structure          $structure
      * @param EncryptorInterface $encryptor
-     * @param Writer $writer
-     * @param Random $random
-     * @param ConfigInterface $indexerConfig
-     * @param EncoderInterface $encoder
-     * @param CollectionFactory $indexerStateCollection
-     * @param string $connectionName
-     * 
+     * @param Writer             $writer
+     * @param Random             $random
+     * @param ConfigInterface    $indexerConfig
+     * @param EncoderInterface   $encoder
+     * @param CollectionFactory  $indexerStateCollection
+     * @param string             $connectionName
+     *
      * @SuppressWarnings(PHPMD.ExcessiveParameterList)
      */
     public function __construct(
@@ -146,11 +146,11 @@ protected function _construct()
     /**
      * Change encryption key
      *
-     * @param string|null $key
-     * @return null|string
-     * @throws FileSystemException|LocalizedException|Exception
+     * @param      string|null $key
+     * @return     null|string
+     * @throws     FileSystemException|LocalizedException|Exception
      * @deprecated
-     * @see Extensible Reencryption Mechanism
+     * @see        Extensible Reencryption Mechanism
      */
     public function changeEncryptionKey($key = null)
     {
@@ -188,14 +188,16 @@ public function changeEncryptionKey($key = null)
     /**
      * Gather all encrypted system config values and re-encrypt them
      *
-     * @return void
+     * @return     void
      * @deprecated
-     * @see Extensible Reencryption Mechanism
+     * @see        Extensible Reencryption Mechanism
      */
     protected function _reEncryptSystemConfigurationValues()
     {
         // look for encrypted node entries in all system.xml files
-        /** @var Structure $configStructure  */
+        /**
+         * @var Structure $configStructure
+        */
         $configStructure = $this->structure;
         $paths = $configStructure->getFieldPathsByAttribute(
             'backend_model',
@@ -225,9 +227,9 @@ protected function _reEncryptSystemConfigurationValues()
     /**
      * Gather saved credit card numbers from sales order payments and re-encrypt them
      *
-     * @return void
+     * @return     void
      * @deprecated
-     * @see Extensible Reencryption Mechanism
+     * @see        Extensible Reencryption Mechanism
      */
     protected function _reEncryptCreditCardNumbers()
     {
@@ -256,7 +258,9 @@ protected function _updateIndexersHash()
         $stateIndexers = [];
         $stateCollection = $this->indexerStateCollection->create();
         foreach ($stateCollection->getItems() as $state) {
-            /** @var \Magento\Indexer\Model\Indexer\State $state */
+            /**
+             * @var \Magento\Indexer\Model\Indexer\State $state
+            */
             $stateIndexers[$state->getIndexerId()] = $state;
         }
         
diff --git a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
index ab31ac45da692..bc01445c7e9a5 100644
--- a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
+++ b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
@@ -136,7 +136,7 @@ protected function setUp(): void
                 'random' => $this->randomMock,
                 'indexerConfig' => $this->indexerConfigMock,
                 'encoder' => $this->encoderMock,
-                'indexerStateCollection' => $this->indexerStateCollectionMock,
+                'indexerStateCollection' => $this->indexerStateCollectionMock
             ]
         );
     }

From d50163685b35f89fa1a4fe24e7a37bbac6321cb1 Mon Sep 17 00:00:00 2001
From: Senthilkumar Muppidathi <senthil@Senthilkumars-MacBook-Pro.local>
Date: Thu, 16 Jan 2025 13:43:37 +0530
Subject: [PATCH 7/9] Adding Adobe copyright instead of magento

---
 .../Test/Unit/Model/ResourceModel/Key/ChangeTest.php          | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
index bc01445c7e9a5..0c614542ecf15 100644
--- a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
+++ b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
@@ -1,7 +1,7 @@
 <?php
 /**
- * Copyright © Magento, Inc. All rights reserved.
- * See COPYING.txt for license details.
+ * Copyright 2015 Adobe
+ * All Rights Reserved.
  */
 declare(strict_types=1);
 

From 195ba0b13aaff82fd6a18640ec8dce61c87a7274 Mon Sep 17 00:00:00 2001
From: Senthilkumar Muppidathi <senthil@Senthilkumars-MacBook-Pro.local>
Date: Fri, 17 Jan 2025 09:15:48 +0530
Subject: [PATCH 8/9] Adding backward compatibility

---
 .../Model/ResourceModel/Key/Change.php           | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
index b4bca5c03b6c3..620f112fc1099 100644
--- a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
+++ b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
@@ -117,9 +117,9 @@ public function __construct(
         EncryptorInterface $encryptor,
         Writer $writer,
         Random $random,
-        ConfigInterface $indexerConfig,
-        EncoderInterface $encoder,
-        CollectionFactory $indexerStateCollection,
+        ConfigInterface $indexerConfig  = null,
+        EncoderInterface $encoder  = null,
+        CollectionFactory $indexerStateCollection  = null,
         $connectionName = null
     ) {
         $this->encryptor = clone $encryptor;
@@ -128,9 +128,10 @@ public function __construct(
         $this->structure = $structure;
         $this->writer = $writer;
         $this->random = $random;
-        $this->indexerConfig = $indexerConfig;
-        $this->encoder = $encoder;
-        $this->indexerStateCollection = $indexerStateCollection;
+
+        $this->indexerConfig = $indexerConfig ?: ObjectManager::getInstance()->get(ConfigInterface::class);
+        $this->encoder = $encoder ?: ObjectManager::getInstance()->get(EncoderInterface::class);
+        $this->indexerStateCollection = $indexerStateCollection->create() ?: ObjectManager::getInstance()->create(CollectionFactory::class);
     }
 
     /**
@@ -256,8 +257,7 @@ protected function _updateIndexersHash()
     {
         
         $stateIndexers = [];
-        $stateCollection = $this->indexerStateCollection->create();
-        foreach ($stateCollection->getItems() as $state) {
+        foreach ($this->indexerStateCollection->getItems() as $state) {
             /**
              * @var \Magento\Indexer\Model\Indexer\State $state
             */

From 6afb87d6b50810921b31e40c7f83d725f6a2dabf Mon Sep 17 00:00:00 2001
From: Senthilkumar Muppidathi <senthil@Senthilkumars-MacBook-Pro.local>
Date: Fri, 17 Jan 2025 23:05:16 +0530
Subject: [PATCH 9/9] Unit test fixes and adopting PSR CS for newly introduced
 functions

---
 .../Model/ResourceModel/Key/Change.php        | 40 ++++----
 .../Model/ResourceModel/Key/ChangeTest.php    | 97 +++++++++++++++++--
 2 files changed, 111 insertions(+), 26 deletions(-)

diff --git a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
index 620f112fc1099..32739df016c4a 100644
--- a/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
+++ b/app/code/Magento/EncryptionKey/Model/ResourceModel/Key/Change.php
@@ -97,16 +97,16 @@ class Change extends AbstractDb
     protected $indexerStateCollection;
 
     /**
-     * @param Context            $context
-     * @param Filesystem         $filesystem
-     * @param Structure          $structure
-     * @param EncryptorInterface $encryptor
-     * @param Writer             $writer
-     * @param Random             $random
-     * @param ConfigInterface    $indexerConfig
-     * @param EncoderInterface   $encoder
-     * @param CollectionFactory  $indexerStateCollection
-     * @param string             $connectionName
+     * @param Context                $context
+     * @param Filesystem             $filesystem
+     * @param Structure              $structure
+     * @param EncryptorInterface     $encryptor
+     * @param Writer                 $writer
+     * @param Random                 $random
+     * @param ConfigInterface        $indexerConfig
+     * @param EncoderInterface       $encoder
+     * @param CollectionFactory      $indexerStateCollection
+     * @param string                 $connectionName
      *
      * @SuppressWarnings(PHPMD.ExcessiveParameterList)
      */
@@ -117,9 +117,9 @@ public function __construct(
         EncryptorInterface $encryptor,
         Writer $writer,
         Random $random,
-        ConfigInterface $indexerConfig  = null,
-        EncoderInterface $encoder  = null,
-        CollectionFactory $indexerStateCollection  = null,
+        ConfigInterface $indexerConfig,
+        EncoderInterface $encoder,
+        CollectionFactory $indexerStateCollection,
         $connectionName = null
     ) {
         $this->encryptor = clone $encryptor;
@@ -128,10 +128,9 @@ public function __construct(
         $this->structure = $structure;
         $this->writer = $writer;
         $this->random = $random;
-
-        $this->indexerConfig = $indexerConfig ?: ObjectManager::getInstance()->get(ConfigInterface::class);
-        $this->encoder = $encoder ?: ObjectManager::getInstance()->get(EncoderInterface::class);
-        $this->indexerStateCollection = $indexerStateCollection->create() ?: ObjectManager::getInstance()->create(CollectionFactory::class);
+        $this->indexerConfig = $indexerConfig;
+        $this->encoder = $encoder;
+        $this->indexerStateCollection = $indexerStateCollection;
     }
 
     /**
@@ -176,7 +175,7 @@ public function changeEncryptionKey($key = null)
         try {
             $this->_reEncryptSystemConfigurationValues();
             $this->_reEncryptCreditCardNumbers();
-            $this->_updateIndexersHash();
+            $this->updateIndexersHash();
             $this->writer->saveConfig($configData);
             $this->commit();
             return $key;
@@ -253,11 +252,12 @@ protected function _reEncryptCreditCardNumbers()
      *
      * @return void
      */
-    protected function _updateIndexersHash()
+    protected function updateIndexersHash()
     {
         
         $stateIndexers = [];
-        foreach ($this->indexerStateCollection->getItems() as $state) {
+        $stateCollection = $this->indexerStateCollection->create();
+        foreach ($stateCollection->getItems() as $state) {
             /**
              * @var \Magento\Indexer\Model\Indexer\State $state
             */
diff --git a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
index 0c614542ecf15..e3e7c1f9b371c 100644
--- a/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
+++ b/app/code/Magento/EncryptionKey/Test/Unit/Model/ResourceModel/Key/ChangeTest.php
@@ -1,8 +1,10 @@
 <?php
+
 /**
  * Copyright 2015 Adobe
  * All Rights Reserved.
  */
+
 declare(strict_types=1);
 
 namespace Magento\EncryptionKey\Test\Unit\Model\ResourceModel\Key;
@@ -24,7 +26,9 @@
 use PHPUnit\Framework\TestCase;
 use Magento\Framework\Indexer\ConfigInterface;
 use Magento\Framework\Json\EncoderInterface;
+use Magento\Indexer\Model\ResourceModel\Indexer\State\Collection as StateCollection;
 use Magento\Indexer\Model\ResourceModel\Indexer\State\CollectionFactory;
+use Magento\Indexer\Model\Indexer\State;
 
 /**
  * Test Class For Magento\EncryptionKey\Model\ResourceModel\Key\Change
@@ -68,7 +72,7 @@ class ChangeTest extends TestCase
 
     /** @var ConfigInterface|MockObject */
     protected $indexerConfigMock;
-    
+
     /** @var EncoderInterface|MockObject */
     protected $encoderMock;
 
@@ -118,6 +122,8 @@ protected function setUp(): void
             ->getMockForAbstractClass();
         $this->indexerStateCollectionMock = $this->getMockBuilder(CollectionFactory::class)
             ->disableOriginalConstructor()
+            ->onlyMethods(['create'])
+            ->addMethods(['getItems'])
             ->getMock();
 
         $helper = new ObjectManager($this);
@@ -141,7 +147,11 @@ protected function setUp(): void
         );
     }
 
-    private function setUpChangeEncryptionKey()
+    /**
+     * @param array $indexersData
+     * @param array $states
+     */
+    private function setUpChangeEncryptionKey(array $indexersData, array $states)
     {
         $paths = ['path1', 'path2'];
         $table = ['item1', 'item2'];
@@ -162,19 +172,50 @@ private function setUpChangeEncryptionKey()
         $this->selectMock->expects($this->any())->method('update')->willReturnSelf();
         $this->writerMock->expects($this->once())->method('saveConfig');
         $this->adapterMock->expects($this->once())->method('getTransactionLevel')->willReturn(1);
+
+        $indexerStateCollection = $this->getMockBuilder(StateCollection::class)
+            ->disableOriginalConstructor()
+            ->getMock();
+
+        $this->indexerStateCollectionMock->expects($this->once())
+            ->method('create')->willReturn($indexerStateCollection);
+
+        $finalStates = [];
+
+        foreach ($states as $key => $state) {
+            if (is_callable($state)) {
+                $finalStates[$key] = $state($this);
+            }
+        }
+
+        $indexerStateCollection->method('getItems')
+            ->willReturn($finalStates);
+
+        $this->indexerConfigMock->expects($this->any())->method('getIndexers')->willReturn($indexersData);
     }
 
-    public function testChangeEncryptionKey()
+    /**
+     * @param array $indexersData
+     * @param array $states
+     * @dataProvider loadDataDataProvider
+     */
+    public function testChangeEncryptionKey(array $indexersData, array $states)
     {
-        $this->setUpChangeEncryptionKey();
+
+        $this->setUpChangeEncryptionKey($indexersData, $states);
         $this->randomMock->expects($this->never())->method('getRandomBytes');
         $key = 'key';
         $this->assertEquals($key, $this->model->changeEncryptionKey($key));
     }
 
-    public function testChangeEncryptionKeyAutogenerate()
+    /**
+     * @param array $indexersData
+     * @param array $states
+     * @dataProvider loadDataDataProvider
+     */
+    public function testChangeEncryptionKeyAutogenerate(array $indexersData, array $states)
     {
-        $this->setUpChangeEncryptionKey();
+        $this->setUpChangeEncryptionKey($indexersData, $states);
         $this->randomMock->expects($this->once())->method('getRandomBytes')->willReturn('abc');
         $this->assertEquals(
             ConfigOptionsListConstants::STORE_KEY_ENCODED_RANDOM_STRING_PREFIX . 'abc',
@@ -195,4 +236,48 @@ public function testChangeEncryptionKeyThrowsException()
 
         $this->fail('An expected exception was not signaled.');
     }
+
+    /**
+     * @param array $data
+     * @return MockObject|State
+     */
+    private function getStateMock(array $data = [])
+    {
+        /** @var MockObject|State $state */
+        $state = $this->getMockBuilder(State::class)
+            ->disableOriginalConstructor()
+            ->getMock();
+        if (isset($data['indexer_id'])) {
+            $state->method('getIndexerId')
+                ->willReturn($data['indexer_id']);
+        }
+
+        return $state;
+    }
+
+    /**
+     * @return array
+     */
+    public static function loadDataDataProvider()
+    {
+        return [
+            [
+                'indexersData' => [
+                    'indexer_2' => [
+                        'indexer_id' => 'indexer_2',
+                    ],
+                    'indexer_3' => [
+                        'indexer_id' => 'indexer_3',
+                    ],
+                    'indexer_1' => [
+                        'indexer_id' => 'indexer_1',
+                    ],
+                ],
+                'states' => [
+                    'indexer_2' => static fn (self $testCase) => $testCase->getStateMock(['indexer_id' => 'indexer_2']),
+                    'indexer_3' => static fn (self $testCase) => $testCase->getStateMock(['indexer_id' => 'indexer_3']),
+                ],
+            ]
+        ];
+    }
 }