From ddd8c7d8ecff8893087149543a59b0f7cd0ab06c Mon Sep 17 00:00:00 2001
From: Alex Pott <alex.a.pott@googlemail.com>
Date: Mon, 10 Jan 2022 12:07:03 +0000
Subject: [PATCH] Issue #3106216 by Spokje, longwave, alexpott, apaderno,
 Hardik_Patel_12, daffie: Remove unused variables from core

(cherry picked from commit 2f1c716625c009fff75b033fd96241f85c2f12bd)
---
 core/includes/common.inc                       |  2 +-
 core/includes/install.core.inc                 |  3 +--
 .../Dumper/OptimizedPhpArrayDumper.php         |  4 ++--
 .../ContainerAwareEventDispatcher.php          | 10 +++++-----
 .../Component/ProxyBuilder/ProxyBuilder.php    |  2 +-
 core/lib/Drupal/Core/Access/AccessResult.php   |  4 ++--
 .../Core/Asset/LibraryDiscoveryParser.php      |  2 +-
 core/lib/Drupal/Core/Database/Database.php     |  2 +-
 .../Drupal/Core/Entity/ContentEntityBase.php   |  2 +-
 .../Entity/EntityConstraintViolationList.php   |  2 +-
 .../Drupal/Core/Entity/EntityDisplayBase.php   |  2 +-
 .../Drupal/Core/Entity/EntityStorageBase.php   |  2 +-
 .../Core/Extension/ExtensionDiscovery.php      |  2 +-
 .../Drupal/Core/Extension/ExtensionList.php    |  2 +-
 .../Core/Extension/ModuleExtensionList.php     |  2 +-
 .../Drupal/Core/Extension/ModuleInstaller.php  |  2 +-
 .../Core/Extension/ThemeExtensionList.php      |  2 +-
 .../Field/FieldType/EntityReferenceItem.php    |  2 +-
 core/lib/Drupal/Core/Flood/DatabaseBackend.php |  2 +-
 core/lib/Drupal/Core/Form/FormErrorHandler.php |  3 ++-
 .../Core/Menu/MenuParentFormSelector.php       |  2 +-
 core/lib/Drupal/Core/Template/Attribute.php    |  2 +-
 .../TestHttpClientMiddleware.php               |  2 +-
 .../RecursiveContextualValidator.php           |  2 +-
 core/misc/cspell/dictionary.txt                |  1 +
 .../Plugin/migrate/process/BlockPluginId.php   |  2 +-
 ...EditingRedundantTagsConstraintValidator.php |  2 +-
 core/modules/comment/comment.module            |  2 +-
 core/modules/comment/src/Entity/Comment.php    |  2 +-
 .../content_moderation/src/Permissions.php     |  2 +-
 .../content_moderation/src/ViewsData.php       |  2 +-
 core/modules/editor/editor.module              |  8 ++++----
 core/modules/field/field.purge.inc             |  1 -
 .../field_ui/src/Element/FieldUiTable.php      |  1 +
 .../file/src/FileAccessControlHandler.php      |  2 +-
 .../FieldFormatter/RSSEnclosureFormatter.php   |  2 +-
 .../Field/FieldFormatter/TableFormatter.php    |  2 +-
 .../filter/src/Plugin/Filter/FilterHtml.php    |  2 +-
 .../ResourceIdentifierNormalizer.php           |  5 +----
 .../Entity/LayoutBuilderEntityViewDisplay.php  |  4 ++--
 .../LayoutBuilderEntityViewDisplayStorage.php  |  2 +-
 .../src/Field/LayoutSectionItemList.php        |  2 +-
 .../locale/src/Form/TranslationStatusForm.php  |  2 +-
 .../src/Controller/OEmbedIframeController.php  |  2 +-
 core/modules/media/src/OEmbed/UrlResolver.php  |  2 +-
 .../src/Plugin/migrate/process/ArrayBuild.php  |  2 +-
 .../src/Plugin/migrate/source/SqlBase.php      |  3 ---
 .../migrate_drupal/src/MigrationState.php      |  2 +-
 .../node/src/NodeAccessControlHandler.php      |  2 +-
 core/modules/rdf/rdf.module                    |  2 --
 .../resource/EntityResourceAccessTrait.php     |  2 +-
 core/modules/system/system.post_update.php     |  2 +-
 .../taxonomy/src/Form/OverviewTerms.php        |  1 +
 .../EntityReferenceSelection/TermSelection.php |  2 +-
 ...EntityReferenceTaxonomyTermRssFormatter.php |  2 +-
 .../src/Controller/ToolbarController.php       |  2 +-
 .../d6/ProfileFieldOptionTranslation.php       |  2 +-
 core/modules/user/src/RegisterForm.php         |  1 -
 .../ViewsEntitySchemaSubscriber.php            |  2 +-
 .../src/Plugin/views/cache/CachePluginBase.php |  2 +-
 .../Plugin/views/display/DisplayPluginBase.php |  2 +-
 .../Plugin/views/display/PathPluginBase.php    |  9 +++------
 .../exposed_form/ExposedFormPluginBase.php     |  2 +-
 .../src/Plugin/views/query/QueryPluginBase.php |  2 +-
 .../views/src/Plugin/views/query/Sql.php       |  2 +-
 .../views/src/Plugin/views/style/Table.php     |  2 +-
 .../src/Controller/ViewsUIController.php       |  2 +-
 core/modules/workspaces/src/EntityTypeInfo.php |  2 +-
 .../src/WorkspacesServiceProvider.php          |  2 +-
 core/phpcs.xml.dist                            | 18 ++++++++++++++++++
 core/scripts/db-tools.php                      |  2 +-
 core/scripts/dump-database-d8-mysql.php        |  2 +-
 core/scripts/generate-proxy-class.php          |  2 +-
 core/themes/bartik/color/color.inc             |  1 +
 74 files changed, 100 insertions(+), 91 deletions(-)

diff --git a/core/includes/common.inc b/core/includes/common.inc
index 799a5e97570f..5bc02f1eb71a 100644
--- a/core/includes/common.inc
+++ b/core/includes/common.inc
@@ -543,7 +543,7 @@ function drupal_flush_all_caches($kernel = NULL) {
   $module_handler = \Drupal::moduleHandler();
   // Flush all persistent caches.
   $module_handler->invokeAll('cache_flush');
-  foreach (Cache::getBins() as $service_id => $cache_backend) {
+  foreach (Cache::getBins() as $cache_backend) {
     $cache_backend->deleteAll();
   }
 
diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc
index 6c492363da77..6d83278cfe6a 100644
--- a/core/includes/install.core.inc
+++ b/core/includes/install.core.inc
@@ -1173,7 +1173,7 @@ function install_verify_database_ready() {
   $table = key($system_schema);
 
   $existing_install = FALSE;
-  if ($database = Database::getConnectionInfo()) {
+  if (Database::getConnectionInfo()) {
     try {
       $existing_install = Database::getConnection()->schema()->tableExists($table);
     }
@@ -2424,7 +2424,6 @@ function install_config_revert_install_changes() {
       $config_importer->import();
     }
     catch (ConfigImporterException $e) {
-      global $install_state;
       $messenger = \Drupal::messenger();
       // There are validation errors.
       $messenger->addError(t('The configuration synchronization failed validation.'));
diff --git a/core/lib/Drupal/Component/DependencyInjection/Dumper/OptimizedPhpArrayDumper.php b/core/lib/Drupal/Component/DependencyInjection/Dumper/OptimizedPhpArrayDumper.php
index 889d2667270f..be177a8b8ba4 100644
--- a/core/lib/Drupal/Component/DependencyInjection/Dumper/OptimizedPhpArrayDumper.php
+++ b/core/lib/Drupal/Component/DependencyInjection/Dumper/OptimizedPhpArrayDumper.php
@@ -250,8 +250,8 @@ protected function getServiceDefinition(Definition $definition) {
       $service['shared'] = $definition->isShared();
     }
 
-    if (($decorated = $definition->getDecoratedService()) !== NULL) {
-      throw new InvalidArgumentException("The 'decorated' definition is not supported by the Drupal 8 run-time container. The Container Builder should have resolved that during the DecoratorServicePass compiler pass.");
+    if ($definition->getDecoratedService() !== NULL) {
+      throw new InvalidArgumentException("The 'decorated' definition is not supported by the Drupal run-time container. The Container Builder should have resolved that during the DecoratorServicePass compiler pass.");
     }
 
     if ($callable = $definition->getFactory()) {
diff --git a/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php b/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php
index eda980cfd8ae..323b8e37f29b 100644
--- a/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php
+++ b/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php
@@ -130,8 +130,8 @@ public function dispatch($event/*, string $event_name = NULL*/) {
       }
 
       // Invoke listeners and resolve callables if necessary.
-      foreach ($this->listeners[$event_name] as $priority => &$definitions) {
-        foreach ($definitions as $key => &$definition) {
+      foreach ($this->listeners[$event_name] as &$definitions) {
+        foreach ($definitions as &$definition) {
           if (!isset($definition['callable'])) {
             $definition['callable'] = [$this->container->get($definition['service'][0]), $definition['service'][1]];
           }
@@ -173,8 +173,8 @@ public function getListeners($event_name = NULL): array {
       }
 
       // Collect listeners and resolve callables if necessary.
-      foreach ($this->listeners[$event_name] as $priority => &$definitions) {
-        foreach ($definitions as $key => &$definition) {
+      foreach ($this->listeners[$event_name] as &$definitions) {
+        foreach ($definitions as &$definition) {
           if (!isset($definition['callable'])) {
             $definition['callable'] = [$this->container->get($definition['service'][0]), $definition['service'][1]];
           }
@@ -202,7 +202,7 @@ public function getListenerPriority($event_name, $listener): ?int {
     }
     // Resolve service definitions if the listener has not been found so far.
     foreach ($this->listeners[$event_name] as $priority => &$definitions) {
-      foreach ($definitions as $key => &$definition) {
+      foreach ($definitions as &$definition) {
         if (!isset($definition['callable'])) {
           // Once the callable is retrieved we keep it for subsequent method
           // invocations on this class.
diff --git a/core/lib/Drupal/Component/ProxyBuilder/ProxyBuilder.php b/core/lib/Drupal/Component/ProxyBuilder/ProxyBuilder.php
index 65d7926e6d56..63d72bccb473 100644
--- a/core/lib/Drupal/Component/ProxyBuilder/ProxyBuilder.php
+++ b/core/lib/Drupal/Component/ProxyBuilder/ProxyBuilder.php
@@ -79,7 +79,7 @@ public function build($class_name) {
     // In order to avoid that, check for each interface, whether one of its
     // parents is also in the list and exclude it.
     if ($interfaces = $reflection->getInterfaces()) {
-      foreach ($interfaces as $interface_name => $interface) {
+      foreach ($interfaces as $interface) {
         // Exclude all parents from the list of implemented interfaces of the
         // class.
         if ($parent_interfaces = $interface->getInterfaceNames()) {
diff --git a/core/lib/Drupal/Core/Access/AccessResult.php b/core/lib/Drupal/Core/Access/AccessResult.php
index 29836fbd6c04..ee7d96a68360 100644
--- a/core/lib/Drupal/Core/Access/AccessResult.php
+++ b/core/lib/Drupal/Core/Access/AccessResult.php
@@ -143,7 +143,7 @@ public static function allowedIfHasPermissions(AccountInterface $account, array
     if ($conjunction == 'AND' && !empty($permissions)) {
       $access = TRUE;
       foreach ($permissions as $permission) {
-        if (!$permission_access = $account->hasPermission($permission)) {
+        if (!$account->hasPermission($permission)) {
           $access = FALSE;
           break;
         }
@@ -151,7 +151,7 @@ public static function allowedIfHasPermissions(AccountInterface $account, array
     }
     else {
       foreach ($permissions as $permission) {
-        if ($permission_access = $account->hasPermission($permission)) {
+        if ($account->hasPermission($permission)) {
           $access = TRUE;
           break;
         }
diff --git a/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php b/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php
index 9392d565109c..0c7953593858 100644
--- a/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php
+++ b/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php
@@ -544,7 +544,7 @@ public static function validateCssLibrary($library) {
         return 2;
       }
       $categories[] = $category;
-      foreach ($files as $source => $options) {
+      foreach ($files as $options) {
         if (!is_array($options)) {
           return 1;
         }
diff --git a/core/lib/Drupal/Core/Database/Database.php b/core/lib/Drupal/Core/Database/Database.php
index 79b681dc883a..96af8c5741d9 100644
--- a/core/lib/Drupal/Core/Database/Database.php
+++ b/core/lib/Drupal/Core/Database/Database.php
@@ -398,7 +398,7 @@ final protected static function openConnection($key, $target) {
       throw new ConnectionNotDefinedException('The specified database connection is not defined: ' . $key);
     }
 
-    if (!$driver = self::$databaseInfo[$key][$target]['driver']) {
+    if (!self::$databaseInfo[$key][$target]['driver']) {
       throw new DriverNotSpecifiedException('Driver not specified for this database connection: ' . $key);
     }
 
diff --git a/core/lib/Drupal/Core/Entity/ContentEntityBase.php b/core/lib/Drupal/Core/Entity/ContentEntityBase.php
index ee965898bc6a..75dd42564b2b 100644
--- a/core/lib/Drupal/Core/Entity/ContentEntityBase.php
+++ b/core/lib/Drupal/Core/Entity/ContentEntityBase.php
@@ -769,7 +769,7 @@ protected function setDefaultLangcode() {
    * Updates language for already instantiated fields.
    */
   protected function updateFieldLangcodes($langcode) {
-    foreach ($this->fields as $name => $items) {
+    foreach ($this->fields as $items) {
       if (!empty($items[LanguageInterface::LANGCODE_DEFAULT])) {
         $items[LanguageInterface::LANGCODE_DEFAULT]->setLangcode($langcode);
       }
diff --git a/core/lib/Drupal/Core/Entity/EntityConstraintViolationList.php b/core/lib/Drupal/Core/Entity/EntityConstraintViolationList.php
index aaa26ecfc708..c31a4044145c 100644
--- a/core/lib/Drupal/Core/Entity/EntityConstraintViolationList.php
+++ b/core/lib/Drupal/Core/Entity/EntityConstraintViolationList.php
@@ -106,7 +106,7 @@ public function getByField($field_name) {
   public function getByFields(array $field_names) {
     $this->groupViolationOffsets();
     $violations = [];
-    foreach (array_intersect_key($this->violationOffsetsByField, array_flip($field_names)) as $field_name => $offsets) {
+    foreach (array_intersect_key($this->violationOffsetsByField, array_flip($field_names)) as $offsets) {
       foreach ($offsets as $offset) {
         $violations[] = $this->get($offset);
       }
diff --git a/core/lib/Drupal/Core/Entity/EntityDisplayBase.php b/core/lib/Drupal/Core/Entity/EntityDisplayBase.php
index 7dce1ff3c307..ee078171871f 100644
--- a/core/lib/Drupal/Core/Entity/EntityDisplayBase.php
+++ b/core/lib/Drupal/Core/Entity/EntityDisplayBase.php
@@ -276,7 +276,7 @@ public function calculateDependencies() {
     if (\Drupal::moduleHandler()->moduleExists('field')) {
       $components = $this->content + $this->hidden;
       $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($this->targetEntityType, $this->bundle);
-      foreach (array_intersect_key($field_definitions, $components) as $field_name => $field_definition) {
+      foreach (array_intersect_key($field_definitions, $components) as $field_definition) {
         if ($field_definition instanceof ConfigEntityInterface && $field_definition->getEntityTypeId() == 'field_config') {
           $this->addDependency('config', $field_definition->getConfigDependencyName());
         }
diff --git a/core/lib/Drupal/Core/Entity/EntityStorageBase.php b/core/lib/Drupal/Core/Entity/EntityStorageBase.php
index ce9e78c53a3e..6fccb37b11b4 100644
--- a/core/lib/Drupal/Core/Entity/EntityStorageBase.php
+++ b/core/lib/Drupal/Core/Entity/EntityStorageBase.php
@@ -229,7 +229,7 @@ protected function getFromStaticCache(array $ids) {
    */
   protected function setStaticCache(array $entities) {
     if ($this->entityType->isStaticallyCacheable()) {
-      foreach ($entities as $id => $entity) {
+      foreach ($entities as $entity) {
         $this->memoryCache->set($this->buildCacheId($entity->id()), $entity, MemoryCacheInterface::CACHE_PERMANENT, [$this->memoryCacheTag]);
       }
     }
diff --git a/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php b/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php
index 266886ba954d..42cbb5713f56 100644
--- a/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php
+++ b/core/lib/Drupal/Core/Extension/ExtensionDiscovery.php
@@ -279,7 +279,7 @@ protected function filterByProfileDirectories(array $all_files) {
         return TRUE;
       }
 
-      foreach ($this->profileDirectories as $weight => $profile_path) {
+      foreach ($this->profileDirectories as $profile_path) {
         if (strpos($file->getPath(), $profile_path) === 0) {
           // Parent profile found.
           return TRUE;
diff --git a/core/lib/Drupal/Core/Extension/ExtensionList.php b/core/lib/Drupal/Core/Extension/ExtensionList.php
index dd538d1c9198..0ac671965b20 100644
--- a/core/lib/Drupal/Core/Extension/ExtensionList.php
+++ b/core/lib/Drupal/Core/Extension/ExtensionList.php
@@ -312,7 +312,7 @@ protected function doList() {
     $extensions = $this->doScanExtensions();
 
     // Read info files for each extension.
-    foreach ($extensions as $extension_name => $extension) {
+    foreach ($extensions as $extension) {
       $extension->info = $this->createExtensionInfo($extension);
 
       // Invoke hook_system_info_alter() to give installed modules a chance to
diff --git a/core/lib/Drupal/Core/Extension/ModuleExtensionList.php b/core/lib/Drupal/Core/Extension/ModuleExtensionList.php
index 5aed60c0b04c..6337cd08940b 100644
--- a/core/lib/Drupal/Core/Extension/ModuleExtensionList.php
+++ b/core/lib/Drupal/Core/Extension/ModuleExtensionList.php
@@ -88,7 +88,7 @@ public function __construct($root, $type, CacheBackendInterface $cache, InfoPars
   protected function getExtensionDiscovery() {
     $discovery = parent::getExtensionDiscovery();
 
-    if ($active_profile = $this->getActiveProfile()) {
+    if ($this->getActiveProfile()) {
       $discovery->setProfileDirectories($this->getProfileDirectories($discovery));
     }
 
diff --git a/core/lib/Drupal/Core/Extension/ModuleInstaller.php b/core/lib/Drupal/Core/Extension/ModuleInstaller.php
index 21970253e91b..8b24bcdf123c 100644
--- a/core/lib/Drupal/Core/Extension/ModuleInstaller.php
+++ b/core/lib/Drupal/Core/Extension/ModuleInstaller.php
@@ -561,7 +561,7 @@ public function uninstall(array $module_list, $uninstall_dependents = TRUE) {
     // Any cache entry might implicitly depend on the uninstalled modules,
     // so clear all of them explicitly.
     $this->moduleHandler->invokeAll('cache_flush');
-    foreach (Cache::getBins() as $service_id => $cache_backend) {
+    foreach (Cache::getBins() as $cache_backend) {
       $cache_backend->deleteAll();
     }
 
diff --git a/core/lib/Drupal/Core/Extension/ThemeExtensionList.php b/core/lib/Drupal/Core/Extension/ThemeExtensionList.php
index 3b065b603d47..e3a427f9c831 100644
--- a/core/lib/Drupal/Core/Extension/ThemeExtensionList.php
+++ b/core/lib/Drupal/Core/Extension/ThemeExtensionList.php
@@ -142,7 +142,7 @@ protected function doList() {
     // sub-themes.
     $this->fillInSubThemeData($themes, $sub_themes);
 
-    foreach ($themes as $key => $theme) {
+    foreach ($themes as $theme) {
       // After $theme is processed by buildModuleDependencies(), there can be a
       // `$theme->requires` array containing both module and base theme
       // dependencies. The module dependencies are copied to their own property
diff --git a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php
index dbe2762d940c..0bf634ea5ea6 100644
--- a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php
+++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php
@@ -345,7 +345,7 @@ public static function generateSampleValue(FieldDefinitionInterface $field_defin
    *   Either the bundle string, or NULL if there is no bundle.
    */
   protected static function getRandomBundle(EntityTypeInterface $entity_type, array $selection_settings) {
-    if ($bundle_key = $entity_type->getKey('bundle')) {
+    if ($entity_type->getKey('bundle')) {
       if (!empty($selection_settings['target_bundles'])) {
         $bundle_ids = $selection_settings['target_bundles'];
       }
diff --git a/core/lib/Drupal/Core/Flood/DatabaseBackend.php b/core/lib/Drupal/Core/Flood/DatabaseBackend.php
index c1da5dd40f47..7caef173e3fc 100644
--- a/core/lib/Drupal/Core/Flood/DatabaseBackend.php
+++ b/core/lib/Drupal/Core/Flood/DatabaseBackend.php
@@ -135,7 +135,7 @@ public function isAllowed($name, $threshold, $window = 3600, $identifier = NULL)
    */
   public function garbageCollection() {
     try {
-      $return = $this->connection->delete(static::TABLE_NAME)
+      $this->connection->delete(static::TABLE_NAME)
         ->condition('expiration', REQUEST_TIME, '<')
         ->execute();
     }
diff --git a/core/lib/Drupal/Core/Form/FormErrorHandler.php b/core/lib/Drupal/Core/Form/FormErrorHandler.php
index 695f023a73bb..dfb52c072ee0 100644
--- a/core/lib/Drupal/Core/Form/FormErrorHandler.php
+++ b/core/lib/Drupal/Core/Form/FormErrorHandler.php
@@ -18,7 +18,7 @@ class FormErrorHandler implements FormErrorHandlerInterface {
    */
   public function handleFormErrors(array &$form, FormStateInterface $form_state) {
     // After validation check if there are errors.
-    if ($errors = $form_state->getErrors()) {
+    if ($form_state->getErrors()) {
       // Display error messages for each element.
       $this->displayErrorMessages($form, $form_state);
 
@@ -110,6 +110,7 @@ protected function setElementErrorsFromFormState(array &$form, FormStateInterfac
     // modify the original form. When processing grouped elements a reference to
     // the complete form is needed.
     if (empty($elements)) {
+      // phpcs:ignore DrupalPractice.CodeAnalysis.VariableAnalysis.VariableRedeclaration
       $elements = &$form;
     }
 
diff --git a/core/lib/Drupal/Core/Menu/MenuParentFormSelector.php b/core/lib/Drupal/Core/Menu/MenuParentFormSelector.php
index ecae57c7cd36..bf8ca0f1400d 100644
--- a/core/lib/Drupal/Core/Menu/MenuParentFormSelector.php
+++ b/core/lib/Drupal/Core/Menu/MenuParentFormSelector.php
@@ -88,7 +88,7 @@ public function parentSelectElement($menu_parent, $id = '', array $menus = NULL)
       if (!isset($options[$menu_parent])) {
         // The requested menu parent cannot be found in the menu anymore. Try
         // setting it to the top level in the current menu.
-        [$menu_name, $parent] = explode(':', $menu_parent, 2);
+        [$menu_name] = explode(':', $menu_parent, 2);
         $menu_parent = $menu_name . ':';
       }
       if (isset($options[$menu_parent])) {
diff --git a/core/lib/Drupal/Core/Template/Attribute.php b/core/lib/Drupal/Core/Template/Attribute.php
index 1ad25dd9cda8..aeb044a3b4a1 100644
--- a/core/lib/Drupal/Core/Template/Attribute.php
+++ b/core/lib/Drupal/Core/Template/Attribute.php
@@ -320,7 +320,7 @@ public function hasClass($class) {
   public function __toString() {
     $return = '';
     /** @var \Drupal\Core\Template\AttributeValueBase $value */
-    foreach ($this->storage as $name => $value) {
+    foreach ($this->storage as $value) {
       $rendered = $value->render();
       if ($rendered) {
         $return .= ' ' . $rendered;
diff --git a/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php b/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php
index ff13f50aeb79..51eb7b76b456 100644
--- a/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php
+++ b/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php
@@ -29,7 +29,7 @@ public function __invoke() {
           $request = $request->withHeader('User-Agent', drupal_generate_test_ua($test_prefix));
         }
         return $handler($request, $options)
-          ->then(function (ResponseInterface $response) use ($request) {
+          ->then(function (ResponseInterface $response) {
             if (!drupal_valid_test_ua()) {
               return $response;
             }
diff --git a/core/lib/Drupal/Core/TypedData/Validation/RecursiveContextualValidator.php b/core/lib/Drupal/Core/TypedData/Validation/RecursiveContextualValidator.php
index 90513008f302..5a8ab698432a 100644
--- a/core/lib/Drupal/Core/TypedData/Validation/RecursiveContextualValidator.php
+++ b/core/lib/Drupal/Core/TypedData/Validation/RecursiveContextualValidator.php
@@ -154,7 +154,7 @@ protected function validateNode(TypedDataInterface $data, $constraints = NULL, $
     // entity, since we should determine whether the entity matches the
     // constraints and not whether the entity validates.
     if (($data instanceof ListInterface || $data instanceof ComplexDataInterface) && !$data->isEmpty() && !($data instanceof EntityAdapter && $constraints_given)) {
-      foreach ($data as $name => $property) {
+      foreach ($data as $property) {
         $this->validateNode($property);
       }
     }
diff --git a/core/misc/cspell/dictionary.txt b/core/misc/cspell/dictionary.txt
index feb5bba6ee69..21ff68e978bf 100644
--- a/core/misc/cspell/dictionary.txt
+++ b/core/misc/cspell/dictionary.txt
@@ -1119,6 +1119,7 @@ realword
 rebuilder
 reclosed
 recolorable
+redeclaration
 redirections
 redstrawberryhiddenfield
 refactorings
diff --git a/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php b/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php
index 1e471a2cf72b..73444dfab1fd 100644
--- a/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php
+++ b/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php
@@ -76,7 +76,7 @@ public function transform($value, MigrateExecutableInterface $migrate_executable
       [$module, $delta] = $value;
       switch ($module) {
         case 'aggregator':
-          [$type, $id] = explode('-', $delta);
+          [$type] = explode('-', $delta);
           if ($type == 'feed') {
             return 'aggregator_feed_block';
           }
diff --git a/core/modules/ckeditor5/src/Plugin/Validation/Constraint/SourceEditingRedundantTagsConstraintValidator.php b/core/modules/ckeditor5/src/Plugin/Validation/Constraint/SourceEditingRedundantTagsConstraintValidator.php
index 618cd3c5951f..9f3e5bb4e1d3 100644
--- a/core/modules/ckeditor5/src/Plugin/Validation/Constraint/SourceEditingRedundantTagsConstraintValidator.php
+++ b/core/modules/ckeditor5/src/Plugin/Validation/Constraint/SourceEditingRedundantTagsConstraintValidator.php
@@ -82,7 +82,7 @@ public function validate($value, Constraint $constraint) {
   private function pluginsSupplyingTagsMessage(array $tags, array $plugin_definitions): string {
     $message_array = [];
     $message_string = '';
-    foreach ($plugin_definitions as $plugin_id => $definition) {
+    foreach ($plugin_definitions as $definition) {
       if ($definition->hasElements()) {
         $elements_array = HTMLRestrictionsUtilities::allowedElementsStringToHtmlFilterArray(implode('', $definition->getElements()));
         foreach ($elements_array as $tag_name => $tag_config) {
diff --git a/core/modules/comment/comment.module b/core/modules/comment/comment.module
index 71c0202b4214..e1a496ba5742 100644
--- a/core/modules/comment/comment.module
+++ b/core/modules/comment/comment.module
@@ -712,7 +712,7 @@ function comment_entity_view_display_presave(EntityViewDisplayInterface $display
   }
 
   // Disable the comment field formatter when the used view display is disabled.
-  foreach ($storage->loadMultiple() as $id => $view_display) {
+  foreach ($storage->loadMultiple() as $view_display) {
     $changed = FALSE;
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
     foreach ($view_display->getComponents() as $field => $component) {
diff --git a/core/modules/comment/src/Entity/Comment.php b/core/modules/comment/src/Entity/Comment.php
index 2fc615f30808..43123b7a17ff 100644
--- a/core/modules/comment/src/Entity/Comment.php
+++ b/core/modules/comment/src/Entity/Comment.php
@@ -193,7 +193,7 @@ public static function postDelete(EntityStorageInterface $storage, array $entiti
     $comments = $comment_storage->loadMultiple($child_cids);
     $comment_storage->delete($comments);
 
-    foreach ($entities as $id => $entity) {
+    foreach ($entities as $entity) {
       \Drupal::service('comment.statistics')->update($entity);
     }
   }
diff --git a/core/modules/content_moderation/src/Permissions.php b/core/modules/content_moderation/src/Permissions.php
index 68639faf306e..faba77fe6076 100644
--- a/core/modules/content_moderation/src/Permissions.php
+++ b/core/modules/content_moderation/src/Permissions.php
@@ -24,7 +24,7 @@ class Permissions {
   public function transitionPermissions() {
     $permissions = [];
     /** @var \Drupal\workflows\WorkflowInterface $workflow */
-    foreach (Workflow::loadMultipleByType('content_moderation') as $id => $workflow) {
+    foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
       foreach ($workflow->getTypePlugin()->getTransitions() as $transition) {
         $permissions['use ' . $workflow->id() . ' transition ' . $transition->id()] = [
           'title' => $this->t('%workflow workflow: Use %transition transition.', [
diff --git a/core/modules/content_moderation/src/ViewsData.php b/core/modules/content_moderation/src/ViewsData.php
index 49ace2054f20..39b69f8ce211 100644
--- a/core/modules/content_moderation/src/ViewsData.php
+++ b/core/modules/content_moderation/src/ViewsData.php
@@ -55,7 +55,7 @@ public function getViewsData() {
       return $this->moderationInformation->isModeratedEntityType($type);
     });
 
-    foreach ($entity_types_with_moderation as $entity_type_id => $entity_type) {
+    foreach ($entity_types_with_moderation as $entity_type) {
       $table = $entity_type->getDataTable() ?: $entity_type->getBaseTable();
 
       $data[$table]['moderation_state'] = [
diff --git a/core/modules/editor/editor.module b/core/modules/editor/editor.module
index da32ff01cba0..726b3ab456a8 100644
--- a/core/modules/editor/editor.module
+++ b/core/modules/editor/editor.module
@@ -369,7 +369,7 @@ function editor_entity_insert(EntityInterface $entity) {
     return;
   }
   $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
-  foreach ($referenced_files_by_field as $field => $uuids) {
+  foreach ($referenced_files_by_field as $uuids) {
     _editor_record_file_usage($uuids, $entity);
   }
 }
@@ -387,7 +387,7 @@ function editor_entity_update(EntityInterface $entity) {
   // deletion of previous file usages are necessary.
   if (!empty($entity->original) && $entity->getRevisionId() != $entity->original->getRevisionId()) {
     $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
-    foreach ($referenced_files_by_field as $field => $uuids) {
+    foreach ($referenced_files_by_field as $uuids) {
       _editor_record_file_usage($uuids, $entity);
     }
   }
@@ -427,7 +427,7 @@ function editor_entity_delete(EntityInterface $entity) {
     return;
   }
   $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
-  foreach ($referenced_files_by_field as $field => $uuids) {
+  foreach ($referenced_files_by_field as $uuids) {
     _editor_delete_file_usage($uuids, $entity, 0);
   }
 }
@@ -441,7 +441,7 @@ function editor_entity_revision_delete(EntityInterface $entity) {
     return;
   }
   $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
-  foreach ($referenced_files_by_field as $field => $uuids) {
+  foreach ($referenced_files_by_field as $uuids) {
     _editor_delete_file_usage($uuids, $entity, 1);
   }
 }
diff --git a/core/modules/field/field.purge.inc b/core/modules/field/field.purge.inc
index 27c22a461d38..8398f434c889 100644
--- a/core/modules/field/field.purge.inc
+++ b/core/modules/field/field.purge.inc
@@ -77,7 +77,6 @@ function field_purge_batch($batch_size, $field_storage_unique_id = NULL) {
 
   $fields = $deleted_fields_repository->getFieldDefinitions($field_storage_unique_id);
 
-  $info = \Drupal::entityTypeManager()->getDefinitions();
   foreach ($fields as $field) {
     $entity_type = $field->getTargetEntityTypeId();
 
diff --git a/core/modules/field_ui/src/Element/FieldUiTable.php b/core/modules/field_ui/src/Element/FieldUiTable.php
index f921398d04e0..2d234bbc7fb7 100644
--- a/core/modules/field_ui/src/Element/FieldUiTable.php
+++ b/core/modules/field_ui/src/Element/FieldUiTable.php
@@ -70,6 +70,7 @@ public static function tablePreRender($elements) {
           $region_name = call_user_func_array($row['#region_callback'], [&$row]);
 
           // Add the element in the tree.
+          // phpcs:ignore DrupalPractice.CodeAnalysis.VariableAnalysis.UnusedVariable
           $target = &$trees[$region_name][''];
           foreach ($parents[$name] as $key) {
             $target = &$target['children'][$key];
diff --git a/core/modules/file/src/FileAccessControlHandler.php b/core/modules/file/src/FileAccessControlHandler.php
index e5c444dc3e9f..3e1fb492d69c 100644
--- a/core/modules/file/src/FileAccessControlHandler.php
+++ b/core/modules/file/src/FileAccessControlHandler.php
@@ -31,7 +31,7 @@ protected function checkAccess(EntityInterface $entity, $operation, AccountInter
       }
       elseif ($references = $this->getFileReferences($entity)) {
         foreach ($references as $field_name => $entity_map) {
-          foreach ($entity_map as $referencing_entity_type => $referencing_entities) {
+          foreach ($entity_map as $referencing_entities) {
             /** @var \Drupal\Core\Entity\EntityInterface $referencing_entity */
             foreach ($referencing_entities as $referencing_entity) {
               $entity_and_field_access = $referencing_entity->access('view', $account, TRUE)->andIf($referencing_entity->$field_name->access('view', $account, TRUE));
diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php
index 12d055114c76..5d2a03e0b1b6 100644
--- a/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php
+++ b/core/modules/file/src/Plugin/Field/FieldFormatter/RSSEnclosureFormatter.php
@@ -24,7 +24,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
     $entity = $items->getEntity();
     // Add the first file as an enclosure to the RSS item. RSS allows only one
     // enclosure per item. See: http://wikipedia.org/wiki/RSS_enclosure
-    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
+    foreach ($this->getEntitiesToView($items, $langcode) as $file) {
       /** @var \Drupal\file\FileInterface $file */
       $entity->rss_elements[] = [
         'key' => 'enclosure',
diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php b/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php
index 5bb3d9488397..e6a8db603877 100644
--- a/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php
+++ b/core/modules/file/src/Plugin/Field/FieldFormatter/TableFormatter.php
@@ -26,7 +26,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
     if ($files = $this->getEntitiesToView($items, $langcode)) {
       $header = [t('Attachment'), t('Size')];
       $rows = [];
-      foreach ($files as $delta => $file) {
+      foreach ($files as $file) {
         $item = $file->_referringItem;
         $rows[] = [
           [
diff --git a/core/modules/filter/src/Plugin/Filter/FilterHtml.php b/core/modules/filter/src/Plugin/Filter/FilterHtml.php
index a40e048d41fb..1db9d1c76122 100644
--- a/core/modules/filter/src/Plugin/Filter/FilterHtml.php
+++ b/core/modules/filter/src/Plugin/Filter/FilterHtml.php
@@ -285,7 +285,7 @@ public function getHTMLRestrictions() {
           // allowed attribute values with a wildcard. A wildcard by itself
           // would mean allowing all possible attribute values. But in that
           // case, one would not specify an attribute value at all.
-          $allowed_attribute_values = array_filter($allowed_attribute_values, function ($value) use ($star_protector) {
+          $allowed_attribute_values = array_filter($allowed_attribute_values, function ($value) {
             return $value !== '*';
           });
 
diff --git a/core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php b/core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php
index d9938339aaf7..cdaa34ac522c 100644
--- a/core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php
+++ b/core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php
@@ -77,9 +77,6 @@ public function denormalize($data, $class, $format = NULL, array $context = [])
     }
     /** @var \Drupal\field\Entity\FieldConfig $field_definition */
     $field_definition = $field_definitions[$context['related']];
-    // This is typically 'target_id'.
-    $item_definition = $field_definition->getItemDefinition();
-    $property_key = $item_definition->getMainPropertyName();
     $target_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($context['related']));
     $target_resource_type_names = array_map(function (ResourceType $resource_type) {
       return $resource_type->getTypeName();
@@ -87,7 +84,7 @@ public function denormalize($data, $class, $format = NULL, array $context = [])
 
     $is_multiple = $field_definition->getFieldStorageDefinition()->isMultiple();
     $data = $this->massageRelationshipInput($data, $is_multiple);
-    $resource_identifiers = array_map(function ($value) use ($property_key, $target_resource_type_names) {
+    $resource_identifiers = array_map(function ($value) use ($target_resource_type_names) {
       // Make sure that the provided type is compatible with the targeted
       // resource.
       if (!in_array($value['type'], $target_resource_type_names)) {
diff --git a/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplay.php b/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplay.php
index 70e86f699913..d543fe161955 100644
--- a/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplay.php
+++ b/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplay.php
@@ -360,9 +360,9 @@ public function label() {
   public function calculateDependencies() {
     parent::calculateDependencies();
 
-    foreach ($this->getSections() as $delta => $section) {
+    foreach ($this->getSections() as $section) {
       $this->calculatePluginDependencies($section->getLayout());
-      foreach ($section->getComponents() as $uuid => $component) {
+      foreach ($section->getComponents() as $component) {
         $this->calculatePluginDependencies($component->getPlugin());
       }
     }
diff --git a/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplayStorage.php b/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplayStorage.php
index d701213f9eec..a221f51fc634 100644
--- a/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplayStorage.php
+++ b/core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplayStorage.php
@@ -32,7 +32,7 @@ protected function mapToStorageRecord(EntityInterface $entity) {
    * {@inheritdoc}
    */
   protected function mapFromStorageRecords(array $records) {
-    foreach ($records as $id => &$record) {
+    foreach ($records as &$record) {
       if (!empty($record['third_party_settings']['layout_builder']['sections'])) {
         $sections = &$record['third_party_settings']['layout_builder']['sections'];
         $sections = array_map([Section::class, 'fromArray'], $sections);
diff --git a/core/modules/layout_builder/src/Field/LayoutSectionItemList.php b/core/modules/layout_builder/src/Field/LayoutSectionItemList.php
index 9870bc41b39e..111acd0f1cc4 100644
--- a/core/modules/layout_builder/src/Field/LayoutSectionItemList.php
+++ b/core/modules/layout_builder/src/Field/LayoutSectionItemList.php
@@ -73,7 +73,7 @@ public function preSave() {
     parent::preSave();
     // Loop through each section and reconstruct it to ensure that all default
     // values are present.
-    foreach ($this->list as $delta => $item) {
+    foreach ($this->list as $item) {
       $item->section = Section::fromArray($item->section->toArray());
     }
   }
diff --git a/core/modules/locale/src/Form/TranslationStatusForm.php b/core/modules/locale/src/Form/TranslationStatusForm.php
index e354153dfd75..4fd147ca22f2 100644
--- a/core/modules/locale/src/Form/TranslationStatusForm.php
+++ b/core/modules/locale/src/Form/TranslationStatusForm.php
@@ -195,7 +195,7 @@ protected function prepareUpdateData(array $status) {
     $this->moduleHandler->loadInclude('locale', 'compare.inc');
     $project_data = locale_translation_build_projects();
 
-    foreach ($status as $project_id => $project) {
+    foreach ($status as $project) {
       foreach ($project as $langcode => $project_info) {
         // No translation file found for this project-language combination.
         if (empty($project_info->type)) {
diff --git a/core/modules/media/src/Controller/OEmbedIframeController.php b/core/modules/media/src/Controller/OEmbedIframeController.php
index a19d2b65e9be..5e7b12ff3766 100644
--- a/core/modules/media/src/Controller/OEmbedIframeController.php
+++ b/core/modules/media/src/Controller/OEmbedIframeController.php
@@ -171,7 +171,7 @@ public function render(Request $request) {
         '#placeholder_token' => $placeholder_token,
       ];
       $context = new RenderContext();
-      $content = $this->renderer->executeInRenderContext($context, function () use ($resource, $element) {
+      $content = $this->renderer->executeInRenderContext($context, function () use ($element) {
         return $this->renderer->render($element);
       });
       $response
diff --git a/core/modules/media/src/OEmbed/UrlResolver.php b/core/modules/media/src/OEmbed/UrlResolver.php
index eb2e6cffbb3b..055729ab3cb2 100644
--- a/core/modules/media/src/OEmbed/UrlResolver.php
+++ b/core/modules/media/src/OEmbed/UrlResolver.php
@@ -130,7 +130,7 @@ protected function findUrl(\DOMXPath $xpath, $format) {
   public function getProviderByUrl($url) {
     // Check the URL against every scheme of every endpoint of every provider
     // until we find a match.
-    foreach ($this->providers->getAll() as $provider_name => $provider_info) {
+    foreach ($this->providers->getAll() as $provider_info) {
       foreach ($provider_info->getEndpoints() as $endpoint) {
         if ($endpoint->matchUrl($url)) {
           return $provider_info;
diff --git a/core/modules/migrate/src/Plugin/migrate/process/ArrayBuild.php b/core/modules/migrate/src/Plugin/migrate/process/ArrayBuild.php
index d5f9d2febe83..acb83662fba6 100644
--- a/core/modules/migrate/src/Plugin/migrate/process/ArrayBuild.php
+++ b/core/modules/migrate/src/Plugin/migrate/process/ArrayBuild.php
@@ -82,7 +82,7 @@ class ArrayBuild extends ProcessPluginBase {
   public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
     $new_value = [];
 
-    foreach ((array) $value as $old_key => $old_value) {
+    foreach ((array) $value as $old_value) {
       // Checks that $old_value is an array.
       if (!is_array($old_value)) {
         throw new MigrateException("The input should be an array of arrays");
diff --git a/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php b/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php
index 7e4a009d7c22..4a1c35ebc42c 100644
--- a/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php
+++ b/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php
@@ -266,9 +266,6 @@ protected function initializeIterator() {
     if ($this->batch == 0) {
       $this->prepareQuery();
 
-      // Get the key values, for potential use in joining to the map table.
-      $keys = [];
-
       // The rules for determining what conditions to add to the query are as
       // follows (applying first applicable rule):
       // 1. If the map is joinable, join it. We will want to accept all rows
diff --git a/core/modules/migrate_drupal/src/MigrationState.php b/core/modules/migrate_drupal/src/MigrationState.php
index b49ff32dcd5a..ca368684919a 100644
--- a/core/modules/migrate_drupal/src/MigrationState.php
+++ b/core/modules/migrate_drupal/src/MigrationState.php
@@ -382,7 +382,7 @@ protected function buildDeclaredStateBySource($version) {
     $state_by_source = [];
     $dest_by_source = [];
     $states = [static::FINISHED, static::NOT_FINISHED];
-    foreach ($migration_states as $module => $info) {
+    foreach ($migration_states as $info) {
       foreach ($states as $state) {
         if (isset($info[$state][$version])) {
           foreach ($info[$state][$version] as $source => $destination) {
diff --git a/core/modules/node/src/NodeAccessControlHandler.php b/core/modules/node/src/NodeAccessControlHandler.php
index 25b386713188..a3a5e9333ebc 100644
--- a/core/modules/node/src/NodeAccessControlHandler.php
+++ b/core/modules/node/src/NodeAccessControlHandler.php
@@ -141,7 +141,7 @@ protected function checkAccess(EntityInterface $node, $operation, AccountInterfa
       return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
     }
 
-    [$revision_permission_operation, $entity_operation] = static::REVISION_OPERATION_MAP[$operation] ?? [
+    [$revision_permission_operation] = static::REVISION_OPERATION_MAP[$operation] ?? [
       NULL,
       NULL,
     ];
diff --git a/core/modules/rdf/rdf.module b/core/modules/rdf/rdf.module
index 69b5f724ebdd..39209dd0222d 100644
--- a/core/modules/rdf/rdf.module
+++ b/core/modules/rdf/rdf.module
@@ -358,9 +358,7 @@ function rdf_preprocess_node(&$variables) {
       $fields = array_keys(\Drupal::service('comment.manager')->getFields('node'));
       $definitions = array_keys($variables['node']->getFieldDefinitions());
       $valid_fields = array_intersect($fields, $definitions);
-      $count = 0;
       foreach ($valid_fields as $field_name) {
-        $count += $variables['node']->get($field_name)->comment_count;
         // Adds RDFa markup for the comment count near the node title as
         // metadata.
         $comment_count_attributes = rdf_rdfa_attributes($comment_count_mapping, $variables['node']->get($field_name)->comment_count);
diff --git a/core/modules/rest/src/Plugin/rest/resource/EntityResourceAccessTrait.php b/core/modules/rest/src/Plugin/rest/resource/EntityResourceAccessTrait.php
index 7bf8e824e159..32ea8391b48c 100644
--- a/core/modules/rest/src/Plugin/rest/resource/EntityResourceAccessTrait.php
+++ b/core/modules/rest/src/Plugin/rest/resource/EntityResourceAccessTrait.php
@@ -25,7 +25,7 @@ protected function checkEditFieldAccess(EntityInterface $entity) {
     // Only check 'edit' permissions for fields that were actually submitted by
     // the user. Field access makes no difference between 'create' and 'update',
     // so the 'edit' operation is used here.
-    foreach ($entity->_restSubmittedFields as $key => $field_name) {
+    foreach ($entity->_restSubmittedFields as $field_name) {
       if (!$entity->get($field_name)->access('edit')) {
         throw new AccessDeniedHttpException("Access denied on creating field '$field_name'.");
       }
diff --git a/core/modules/system/system.post_update.php b/core/modules/system/system.post_update.php
index a7230ecd2939..e2e467ef97a2 100644
--- a/core/modules/system/system.post_update.php
+++ b/core/modules/system/system.post_update.php
@@ -100,7 +100,7 @@ function system_post_update_entity_revision_metadata_bc_cleanup() {
   });
 
   // Remove the '$requiredRevisionMetadataKeys' property for these entity types.
-  foreach ($last_installed_definitions as $entity_type_id => $entity_type) {
+  foreach ($last_installed_definitions as $entity_type) {
     $closure = function (ContentEntityTypeInterface $entity_type) {
       return get_object_vars($entity_type);
     };
diff --git a/core/modules/taxonomy/src/Form/OverviewTerms.php b/core/modules/taxonomy/src/Form/OverviewTerms.php
index 0b918bf7314e..ebc9e5933c01 100644
--- a/core/modules/taxonomy/src/Form/OverviewTerms.php
+++ b/core/modules/taxonomy/src/Form/OverviewTerms.php
@@ -161,6 +161,7 @@ public function buildForm(array $form, FormStateInterface $form_state, Vocabular
     $term_deltas = [];
     $tree = $this->storageController->loadTree($taxonomy_vocabulary->id(), 0, NULL, TRUE);
     $tree_index = 0;
+    $complete_tree = NULL;
     do {
       // In case this tree is completely empty.
       if (empty($tree[$tree_index])) {
diff --git a/core/modules/taxonomy/src/Plugin/EntityReferenceSelection/TermSelection.php b/core/modules/taxonomy/src/Plugin/EntityReferenceSelection/TermSelection.php
index 1ccee9737a43..295852c3fc11 100644
--- a/core/modules/taxonomy/src/Plugin/EntityReferenceSelection/TermSelection.php
+++ b/core/modules/taxonomy/src/Plugin/EntityReferenceSelection/TermSelection.php
@@ -89,7 +89,7 @@ public function countReferenceableEntities($match = NULL, $match_operator = 'CON
 
     $total = 0;
     $referenceable_entities = $this->getReferenceableEntities($match, $match_operator, 0);
-    foreach ($referenceable_entities as $bundle => $entities) {
+    foreach ($referenceable_entities as $entities) {
       $total += count($entities);
     }
     return $total;
diff --git a/core/modules/taxonomy/src/Plugin/Field/FieldFormatter/EntityReferenceTaxonomyTermRssFormatter.php b/core/modules/taxonomy/src/Plugin/Field/FieldFormatter/EntityReferenceTaxonomyTermRssFormatter.php
index 8d9afeefd3f1..81d1f4b475fe 100644
--- a/core/modules/taxonomy/src/Plugin/Field/FieldFormatter/EntityReferenceTaxonomyTermRssFormatter.php
+++ b/core/modules/taxonomy/src/Plugin/Field/FieldFormatter/EntityReferenceTaxonomyTermRssFormatter.php
@@ -28,7 +28,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
     $parent_entity = $items->getEntity();
     $elements = [];
 
-    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
+    foreach ($this->getEntitiesToView($items, $langcode) as $entity) {
       $parent_entity->rss_elements[] = [
         'key' => 'category',
         'value' => $entity->label(),
diff --git a/core/modules/toolbar/src/Controller/ToolbarController.php b/core/modules/toolbar/src/Controller/ToolbarController.php
index 75986f901b0f..e887c4677976 100644
--- a/core/modules/toolbar/src/Controller/ToolbarController.php
+++ b/core/modules/toolbar/src/Controller/ToolbarController.php
@@ -21,7 +21,7 @@ class ToolbarController extends ControllerBase implements TrustedCallbackInterfa
    * @return \Drupal\Core\Ajax\AjaxResponse
    */
   public function subtreesAjax() {
-    [$subtrees, $cacheability] = toolbar_get_rendered_subtrees();
+    [$subtrees] = toolbar_get_rendered_subtrees();
     $response = new AjaxResponse();
     $response->addCommand(new SetSubtreesCommand($subtrees));
 
diff --git a/core/modules/user/src/Plugin/migrate/process/d6/ProfileFieldOptionTranslation.php b/core/modules/user/src/Plugin/migrate/process/d6/ProfileFieldOptionTranslation.php
index 7087dc4e80b8..4f78e193f020 100644
--- a/core/modules/user/src/Plugin/migrate/process/d6/ProfileFieldOptionTranslation.php
+++ b/core/modules/user/src/Plugin/migrate/process/d6/ProfileFieldOptionTranslation.php
@@ -29,7 +29,7 @@ public function transform($value, MigrateExecutableInterface $migrate_executable
       $list = array_map('trim', $list);
       $list = array_filter($list, 'strlen');
       if ($field_type === 'list_string') {
-        foreach ($list as $key => $value) {
+        foreach ($list as $value) {
           $allowed_values[] = ['label' => $value];
         }
       }
diff --git a/core/modules/user/src/RegisterForm.php b/core/modules/user/src/RegisterForm.php
index f1efe4a79caa..0a4da2dcf1ee 100644
--- a/core/modules/user/src/RegisterForm.php
+++ b/core/modules/user/src/RegisterForm.php
@@ -15,7 +15,6 @@ class RegisterForm extends AccountForm {
    * {@inheritdoc}
    */
   public function form(array $form, FormStateInterface $form_state) {
-    $user = $this->currentUser();
     /** @var \Drupal\user\UserInterface $account */
     $account = $this->entity;
 
diff --git a/core/modules/views/src/EventSubscriber/ViewsEntitySchemaSubscriber.php b/core/modules/views/src/EventSubscriber/ViewsEntitySchemaSubscriber.php
index 52d112d840b5..fbd9f4855bea 100644
--- a/core/modules/views/src/EventSubscriber/ViewsEntitySchemaSubscriber.php
+++ b/core/modules/views/src/EventSubscriber/ViewsEntitySchemaSubscriber.php
@@ -246,7 +246,7 @@ public function onEntityTypeDelete(EntityTypeInterface $entity_type) {
 
     $all_views = $this->entityTypeManager->getStorage('view')->loadMultiple(NULL);
     /** @var \Drupal\views\Entity\View $view */
-    foreach ($all_views as $id => $view) {
+    foreach ($all_views as $view) {
 
       // First check just the base table.
       if (in_array($view->get('base_table'), $tables)) {
diff --git a/core/modules/views/src/Plugin/views/cache/CachePluginBase.php b/core/modules/views/src/Plugin/views/cache/CachePluginBase.php
index 4fe6c872c406..09205f227de7 100644
--- a/core/modules/views/src/Plugin/views/cache/CachePluginBase.php
+++ b/core/modules/views/src/Plugin/views/cache/CachePluginBase.php
@@ -243,7 +243,7 @@ public function getCacheTags() {
 
     if (!empty($entity_information)) {
       // Add the list cache tags for each entity type used by this view.
-      foreach ($entity_information as $table => $metadata) {
+      foreach ($entity_information as $metadata) {
         $tags = Cache::mergeTags($tags, \Drupal::entityTypeManager()->getDefinition($metadata['entity_type'])->getListCacheTags());
       }
     }
diff --git a/core/modules/views/src/Plugin/views/display/DisplayPluginBase.php b/core/modules/views/src/Plugin/views/display/DisplayPluginBase.php
index 4a9f2fbbdd85..338c5fe72d75 100644
--- a/core/modules/views/src/Plugin/views/display/DisplayPluginBase.php
+++ b/core/modules/views/src/Plugin/views/display/DisplayPluginBase.php
@@ -2520,7 +2520,7 @@ public function validate() {
     // Check for missing relationships.
     $relationships = array_keys($this->getHandlers('relationship'));
     foreach (ViewExecutable::getHandlerTypes() as $type => $handler_type_info) {
-      foreach ($this->getHandlers($type) as $handler_id => $handler) {
+      foreach ($this->getHandlers($type) as $handler) {
         if (!empty($handler->options['relationship']) && $handler->options['relationship'] != 'none' && !in_array($handler->options['relationship'], $relationships)) {
           $errors[] = $this->t('The %handler_type %handler uses a relationship that has been removed.', ['%handler_type' => $handler_type_info['lstitle'], '%handler' => $handler->adminLabel()]);
         }
diff --git a/core/modules/views/src/Plugin/views/display/PathPluginBase.php b/core/modules/views/src/Plugin/views/display/PathPluginBase.php
index ca3e6b7dfd67..b8eb284a3b56 100644
--- a/core/modules/views/src/Plugin/views/display/PathPluginBase.php
+++ b/core/modules/views/src/Plugin/views/display/PathPluginBase.php
@@ -338,13 +338,10 @@ public function getMenuLinks() {
 
     // Replace % with %views_arg for menu autoloading and add to the
     // page arguments so the argument actually comes through.
-    foreach ($bits as $pos => $bit) {
-      if ($bit == '%') {
-        // If a view requires any arguments we cannot create a static menu link.
-        return [];
-      }
+    if (in_array('%', $bits, TRUE)) {
+      // If a view requires any arguments we cannot create a static menu link.
+      return [];
     }
-
     $path = implode('/', $bits);
     $view_id = $this->view->storage->id();
     $display_id = $this->display['id'];
diff --git a/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php b/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php
index ff5261cadb79..0892bce15d69 100644
--- a/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php
+++ b/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php
@@ -158,7 +158,7 @@ public function query() {
       // Make sure the original order of sorts is preserved
       // (e.g. a sticky sort is often first)
       $view->query->orderby = [];
-      foreach ($view->sort as $key => $sort) {
+      foreach ($view->sort as $sort) {
         if (!$sort->isExposed()) {
           $sort->query();
         }
diff --git a/core/modules/views/src/Plugin/views/query/QueryPluginBase.php b/core/modules/views/src/Plugin/views/query/QueryPluginBase.php
index 13585fd745a4..27277a5e3e92 100644
--- a/core/modules/views/src/Plugin/views/query/QueryPluginBase.php
+++ b/core/modules/views/src/Plugin/views/query/QueryPluginBase.php
@@ -119,7 +119,7 @@ public function summaryTitle() {
   public function calculateDependencies() {
     $dependencies = [];
 
-    foreach ($this->getEntityTableInfo() as $entity_type => $info) {
+    foreach ($this->getEntityTableInfo() as $info) {
       if (!empty($info['provider'])) {
         $dependencies['module'][] = $info['provider'];
       }
diff --git a/core/modules/views/src/Plugin/views/query/Sql.php b/core/modules/views/src/Plugin/views/query/Sql.php
index 0a639958893b..978d5fe116ca 100644
--- a/core/modules/views/src/Plugin/views/query/Sql.php
+++ b/core/modules/views/src/Plugin/views/query/Sql.php
@@ -1357,7 +1357,7 @@ public function query($get_count = FALSE) {
         ];
       }
 
-      foreach ($entity_information as $entity_type_id => $info) {
+      foreach ($entity_information as $info) {
         $entity_type = \Drupal::entityTypeManager()->getDefinition($info['entity_type']);
         $base_field = !$info['revision'] ? $entity_type->getKey('id') : $entity_type->getKey('revision');
         $this->addField($info['alias'], $base_field, '', $params);
diff --git a/core/modules/views/src/Plugin/views/style/Table.php b/core/modules/views/src/Plugin/views/style/Table.php
index 11552188ddaa..fb75b0dedd79 100644
--- a/core/modules/views/src/Plugin/views/style/Table.php
+++ b/core/modules/views/src/Plugin/views/style/Table.php
@@ -433,7 +433,7 @@ public function getCacheMaxAge() {
   public function getCacheContexts() {
     $contexts = [];
 
-    foreach ($this->options['info'] as $field_id => $info) {
+    foreach ($this->options['info'] as $info) {
       if (!empty($info['sortable'])) {
         // The rendered link needs to play well with any other query parameter
         // used on the page, like pager and exposed filter.
diff --git a/core/modules/views_ui/src/Controller/ViewsUIController.php b/core/modules/views_ui/src/Controller/ViewsUIController.php
index c5ccdf23b32d..b81bf4317554 100644
--- a/core/modules/views_ui/src/Controller/ViewsUIController.php
+++ b/core/modules/views_ui/src/Controller/ViewsUIController.php
@@ -121,7 +121,7 @@ public function reportPlugins() {
     foreach ($rows as &$row) {
       $views = [];
       // Link each view name to the view itself.
-      foreach ($row['views'] as $row_name => $view) {
+      foreach ($row['views'] as $view) {
         $views[] = Link::fromTextAndUrl($view, new Url('entity.view.edit_form', ['view' => $view]))->toString();
       }
       unset($row['views']);
diff --git a/core/modules/workspaces/src/EntityTypeInfo.php b/core/modules/workspaces/src/EntityTypeInfo.php
index 5052d30899a9..bf9d82fedfad 100644
--- a/core/modules/workspaces/src/EntityTypeInfo.php
+++ b/core/modules/workspaces/src/EntityTypeInfo.php
@@ -83,7 +83,7 @@ public function entityTypeBuild(array &$entity_types) {
    * @see hook_entity_type_alter()
    */
   public function entityTypeAlter(array &$entity_types) {
-    foreach ($entity_types as $entity_type_id => $entity_type) {
+    foreach ($entity_types as $entity_type) {
       // Non-default workspaces display the active revision on the canonical
       // route of an entity, so the latest version route is no longer needed.
       $link_templates = $entity_type->get('links');
diff --git a/core/modules/workspaces/src/WorkspacesServiceProvider.php b/core/modules/workspaces/src/WorkspacesServiceProvider.php
index adc08bbce3ae..e9c869d977c7 100644
--- a/core/modules/workspaces/src/WorkspacesServiceProvider.php
+++ b/core/modules/workspaces/src/WorkspacesServiceProvider.php
@@ -34,7 +34,7 @@ public function alter(ContainerBuilder $container) {
     // Ensure that there's no active workspace while running database updates by
     // removing the relevant tag from all workspace negotiator services.
     if ($container->get('kernel') instanceof UpdateKernel) {
-      foreach ($container->getDefinitions() as $id => $definition) {
+      foreach ($container->getDefinitions() as $definition) {
         if ($definition->hasTag('workspace_negotiator')) {
           $definition->clearTag('workspace_negotiator');
         }
diff --git a/core/phpcs.xml.dist b/core/phpcs.xml.dist
index de9eefb69260..b0782ff6bff8 100644
--- a/core/phpcs.xml.dist
+++ b/core/phpcs.xml.dist
@@ -145,6 +145,24 @@
   <rule ref="DrupalPractice.Commenting.ExpectedException"/>
   <rule ref="DrupalPractice.General.ExceptionT"/>
   <rule ref="DrupalPractice.InfoFiles.NamespacedDependency"/>
+  <rule ref="DrupalPractice.CodeAnalysis.VariableAnalysis">
+    <!-- @todo exclude tests -->
+    <exclude-pattern>*/tests/*</exclude-pattern>
+    <!-- Do not run this sniff on API files or transliteration data. -->
+    <exclude-pattern>*.api.php</exclude-pattern>
+    <exclude-pattern>core/lib/Drupal/Component/Transliteration/data/*.php</exclude-pattern>
+    <properties>
+      <property name="allowUnusedFunctionParameters" value="true"/>
+    </properties>
+  </rule>
+  <rule ref="DrupalPractice.CodeAnalysis.VariableAnalysis.UndefinedVariable">
+    <!-- Setting severity to 0 to completely disable an error message in this sniff, without excluding the whole sniff -->
+    <!-- See https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options#changing-the-default-severity-levels -->
+    <severity>0</severity>
+  </rule>
+  <rule ref="DrupalPractice.CodeAnalysis.VariableAnalysis.UndefinedUnsetVariable">
+    <severity>0</severity>
+  </rule>
 
   <!-- Generic sniffs -->
   <rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
diff --git a/core/scripts/db-tools.php b/core/scripts/db-tools.php
index dccd69ce218d..6efa58dac800 100644
--- a/core/scripts/db-tools.php
+++ b/core/scripts/db-tools.php
@@ -19,7 +19,7 @@
 $autoloader = require __DIR__ . '/../../autoload.php';
 $request = Request::createFromGlobals();
 Settings::initialize(dirname(__DIR__, 2), DrupalKernel::findSitePath($request), $autoloader);
-$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
+DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
 
 // Run the database dump command.
 $application = new DbToolsApplication();
diff --git a/core/scripts/dump-database-d8-mysql.php b/core/scripts/dump-database-d8-mysql.php
index bce5d549bc41..1fd14e807afd 100644
--- a/core/scripts/dump-database-d8-mysql.php
+++ b/core/scripts/dump-database-d8-mysql.php
@@ -19,7 +19,7 @@
 $autoloader = require __DIR__ . '/../../autoload.php';
 $request = Request::createFromGlobals();
 Settings::initialize(dirname(__DIR__, 2), DrupalKernel::findSitePath($request), $autoloader);
-$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
+DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
 
 // Run the database dump command.
 $application = new DbDumpApplication();
diff --git a/core/scripts/generate-proxy-class.php b/core/scripts/generate-proxy-class.php
index d277c34d5ee3..2664739be423 100644
--- a/core/scripts/generate-proxy-class.php
+++ b/core/scripts/generate-proxy-class.php
@@ -20,7 +20,7 @@
 $autoloader = require __DIR__ . '/../../autoload.php';
 $request = Request::createFromGlobals();
 Settings::initialize(dirname(__DIR__, 2), DrupalKernel::findSitePath($request), $autoloader);
-$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
+DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
 
 // Run the database dump command.
 $application = new GenerateProxyClassApplication(new ProxyBuilder());
diff --git a/core/themes/bartik/color/color.inc b/core/themes/bartik/color/color.inc
index 67b092f1600f..d7265944b27c 100644
--- a/core/themes/bartik/color/color.inc
+++ b/core/themes/bartik/color/color.inc
@@ -5,6 +5,7 @@
  * Lists available colors and color schemes for the Bartik theme.
  */
 
+// phpcs:ignore DrupalPractice.CodeAnalysis.VariableAnalysis.UnusedVariable
 $info = [
   // Available colors and color labels used in theme.
   'fields' => [
-- 
GitLab