From e3d1c8ff425d7cc3ecbe01246542208b767692eb Mon Sep 17 00:00:00 2001
From: Andrei Mateescu <2117-amateescu@users.noreply.drupalcode.org>
Date: Wed, 23 Apr 2025 12:14:00 +0000
Subject: [PATCH] Issue #3498216 by ajits, amateescu, plach:
 entity_workflow_workspace doesn't work well with existing workspaces

---
 .../entity_workflow_workspace.install         | 52 +++++++++++++++++++
 1 file changed, 52 insertions(+)
 create mode 100644 modules/entity_workflow_workspace/entity_workflow_workspace.install

diff --git a/modules/entity_workflow_workspace/entity_workflow_workspace.install b/modules/entity_workflow_workspace/entity_workflow_workspace.install
new file mode 100644
index 0000000..6c12dce
--- /dev/null
+++ b/modules/entity_workflow_workspace/entity_workflow_workspace.install
@@ -0,0 +1,52 @@
+<?php
+
+/**
+ * @file
+ * Contains install, update and uninstall functions for the Entity Workflow
+ * Workspace module.
+ */
+
+use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
+
+/**
+ * Implements hook_install().
+ */
+function entity_workflow_workspace_install(): void {
+  // Set the initial workflow state directly if possible.
+  $storage = \Drupal::entityTypeManager()->getStorage('workspace');
+  if (!($storage instanceof SqlContentEntityStorage)) {
+    return;
+  }
+
+  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
+  $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
+  $storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('workspace');
+
+  if (isset($storage_definitions['status']) && $storage_definitions['status']->getProvider() === 'wse') {
+    $open_workspace_ids = $storage->getQuery()
+      ->accessCheck(FALSE)
+      ->condition('status', WSE_STATUS_OPEN)
+      ->execute();
+    $closed_workspace_ids = $storage->getQuery()
+      ->accessCheck(FALSE)
+      ->condition('status', WSE_STATUS_CLOSED)
+      ->execute();
+
+    $database = \Drupal::database();
+    $table_mapping = $storage->getTableMapping();
+    $workflow_column = $table_mapping->getFieldColumnName($storage_definitions['entity_workflow_workspace'], 'value');
+    $id_column = $table_mapping->getFieldColumnName($storage_definitions['id'], 'value');
+    foreach ($table_mapping->getAllFieldTableNames('entity_workflow_workspace') as $table_name) {
+      $database->update($table_name)
+        ->fields([$workflow_column => 'draft'])
+        ->condition($id_column, array_values($open_workspace_ids), 'IN')
+        ->execute();
+      $database->update($table_name)
+        ->fields([$workflow_column => 'published'])
+        ->condition($id_column, array_values($closed_workspace_ids), 'IN')
+        ->execute();
+    }
+
+    $storage->resetCache();
+  }
+}
-- 
GitLab