From effa986b863532f4239bcb45d58a900ad2ffbf1b Mon Sep 17 00:00:00 2001
From: Igor Biki <ibiki@uwaterloo.ca>
Date: Thu, 20 Mar 2025 13:45:19 -0400
Subject: [PATCH] ISTWCMS-7275: Add post-update hook to rename publication
 block titles

This update introduces a post-update hook to rename specific publication block titles within user dashboards for consistency and clarity. It retrieves and updates user data while logging progress and handling potential errors to ensure updates are applied correctly.
---
 uw_dashboard.post_update.php | 65 ++++++++++++++++++++++++++++++++++++
 1 file changed, 65 insertions(+)
 create mode 100644 uw_dashboard.post_update.php

diff --git a/uw_dashboard.post_update.php b/uw_dashboard.post_update.php
new file mode 100644
index 0000000..ebb8b27
--- /dev/null
+++ b/uw_dashboard.post_update.php
@@ -0,0 +1,65 @@
+<?php
+
+/**
+ * @file
+ * Post update hooks for uw_dashboard module.
+ */
+
+/**
+ * Renaming publications blocks titles to reference block titles.
+ */
+function uw_dashboard_post_update_blocks_rename(&$sandbox) {
+  $rename = [
+    'uw_publication_authors_block' => ['Publication reference authors' => 'Reference authors'],
+    'uw_publication_reference_block' => ['Publication references' => 'References'],
+    'uw_publication_keywords_block' => ['Publication reference keywords' => 'Reference keywords'],
+    'uw_cbl_publication_search' => ['Publication reference search' => 'Reference search'],
+  ];
+
+  $database = \Drupal::database();
+
+  $query = $database->select('users_data', 'ud')
+    ->fields('ud', ['uid', 'value'])
+    ->condition('module', 'dashboards')
+    ->condition('name', 'my_dashboard');
+
+  $result = $query->execute()->fetchAllAssoc('uid');
+
+  \Drupal::logger('uw_dashboard')
+    ->info('Updating @num dashboards', ['@num' => count($result)]);
+
+  /** @var \Drupal\user\UserDataInterface $dataService */
+  $dataService = \Drupal::service('user.data');
+
+  foreach ($result as $uid => $row) {
+    try {
+      $data = unserialize($row->value, ['allowed_classes' => FALSE]);
+      $save_required = FALSE;
+
+      foreach ($data as &$section) {
+        foreach ($section['components'] as &$block) {
+          if (array_key_exists($block['configuration']['id'], $rename)) {
+            $titles = $rename[$block['configuration']['id']];
+            foreach ($titles as $old => $new) {
+              if (trim($block['configuration']['label']) === $old) {
+                $block['configuration']['label'] = $new;
+                $save_required = TRUE;
+              }
+            }
+          }
+        }
+      }
+
+      if ($save_required) {
+        $dataService->set('dashboards', $uid, 'my_dashboard', serialize($data));
+      }
+    }
+    catch (\Exception $ex) {
+      \Drupal::logger('uw_dashboard')
+        ->error('Block rename failed for user: @uid, with message: @message', [
+          '@uid' => $uid,
+          '@message' => $ex->getMessage(),
+        ]);
+    }
+  }
+}
-- 
GitLab