From 7b12166b5c15c4b6ee81d8845045957f5607cba3 Mon Sep 17 00:00:00 2001
From: Philipp Stracker
Date: Thu, 20 Feb 2025 14:01:06 +0100
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Allow=20callbacks=20in=20SettingsMa?=
=?UTF-8?q?p=20to=20resolve=20values?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../ppcp-compat/src/Settings/SettingsMap.php | 2 +-
.../src/Settings/SettingsMapHelper.php | 19 ++++++++++++++-----
2 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/modules/ppcp-compat/src/Settings/SettingsMap.php b/modules/ppcp-compat/src/Settings/SettingsMap.php
index 661481b27..59c010cf2 100644
--- a/modules/ppcp-compat/src/Settings/SettingsMap.php
+++ b/modules/ppcp-compat/src/Settings/SettingsMap.php
@@ -14,7 +14,7 @@ use WooCommerce\PayPalCommerce\Settings\Data\AbstractDataModel;
/**
* A map of old to new settings.
*
- * @psalm-type newSettingsKey = string
+ * @psalm-type newSettingsKey = string|callable
* @psalm-type oldSettingsKey = string
*/
class SettingsMap {
diff --git a/modules/ppcp-compat/src/Settings/SettingsMapHelper.php b/modules/ppcp-compat/src/Settings/SettingsMapHelper.php
index 678644897..1df30d4e3 100644
--- a/modules/ppcp-compat/src/Settings/SettingsMapHelper.php
+++ b/modules/ppcp-compat/src/Settings/SettingsMapHelper.php
@@ -134,18 +134,27 @@ class SettingsMapHelper {
/**
* Retrieves a cached model value or caches it if not already cached.
*
- * @param int $model_id The unique identifier for the model object.
- * @param string $old_key The key in the old settings structure.
- * @param string $new_key The key in the new settings structure.
- * @param object $model The model object.
+ * @param int $model_id The unique identifier for the model object.
+ * @param string $old_key The key in the old settings structure.
+ * @param string|callable $new_key The key in the new settings structure.
+ * @param object $model The model object.
*
* @return mixed|null The value of the key in the model, or null if not found.
*/
- protected function get_cached_model_value( int $model_id, string $old_key, string $new_key, object $model ) {
+ protected function get_cached_model_value( int $model_id, string $old_key, $new_key, object $model ) {
if ( ! isset( $this->model_cache[ $model_id ] ) ) {
$this->model_cache[ $model_id ] = $model->to_array();
}
+ if ( is_callable( $new_key ) ) {
+ // Resolve the callback once and store it in the request-cache.
+ if ( ! isset( $this->model_cache[ $model_id ][ $old_key ] ) ) {
+ $this->model_cache[ $model_id ][ $old_key ] = $new_key( $this->model_cache[ $model_id ] );
+ }
+
+ return $this->model_cache[ $model_id ][ $old_key ];
+ }
+
switch ( true ) {
case $model instanceof StylingSettings:
return $this->styling_settings_map_helper->mapped_value( $old_key, $this->model_cache[ $model_id ] );