From e9440f33986176485cb067c048512474c705f013 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:40:49 -0600 Subject: [PATCH 01/10] feat: add opt-in --recurse-keys flag for serialized keys Serialized array keys and object property names now pass through the same replacement branch as values when --recurse-keys is set. Default behavior is unchanged. --- features/search-replace.feature | 122 ++++++++++++++++++++++++++++++++ src/Search_Replace_Command.php | 16 ++++- src/WP_CLI/SearchReplacer.php | 111 ++++++++++++++++++++--------- 3 files changed, 212 insertions(+), 37 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index 5123dded..ab408608 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1592,3 +1592,125 @@ Feature: Do global search/replace """ Table is read-only """ + + @require-mysql + Scenario: Serialized array keys are left alone by default + Given a WP install + And a setup-recurse-keys.php file: + """ + 'https://old.example.com/value', 'nested' => array( 'https://old.example.com/inner' => 'plain' ) ) ); + """ + And a check-recurse-keys.php file: + """ + 'https://old.example.com/value', 'nested' => array( 'https://old.example.com/inner' => 'plain' ) ) ); + """ + And a check-recurse-keys.php file: + """ + 'https://old.example.com/value' ) ); + """ + And a check-recurse-keys-object.php file: + """ + $args Positional arguments. - * @param array{'old'?: string, 'new'?: string, 'dry-run'?: bool, 'network'?: bool, 'all-tables-with-prefix'?: bool, 'all-tables'?: bool, 'export'?: string, 'export_insert_size'?: string, 'skip-tables'?: string, 'skip-columns'?: string, 'include-columns'?: string, 'precise'?: bool, 'recurse-objects'?: bool, 'verbose'?: bool, 'regex'?: bool, 'regex-flags'?: string, 'regex-delimiter'?: string, 'regex-limit'?: string, 'format': string, 'report'?: bool, 'report-changed-only'?: bool, 'log'?: string, 'before_context'?: string, 'after_context'?: string} $assoc_args Associative arguments. + * @param array{'old'?: string, 'new'?: string, 'dry-run'?: bool, 'network'?: bool, 'all-tables-with-prefix'?: bool, 'all-tables'?: bool, 'export'?: string, 'export_insert_size'?: string, 'skip-tables'?: string, 'skip-columns'?: string, 'include-columns'?: string, 'precise'?: bool, 'recurse-objects'?: bool, 'recurse-keys'?: bool, 'verbose'?: bool, 'regex'?: bool, 'regex-flags'?: string, 'regex-delimiter'?: string, 'regex-limit'?: string, 'format': string, 'report'?: bool, 'report-changed-only'?: bool, 'log'?: string, 'before_context'?: string, 'after_context'?: string} $assoc_args Associative arguments. */ public function __invoke( $args, $assoc_args ) { global $wpdb; @@ -337,6 +346,7 @@ public function __invoke( $args, $assoc_args ) { $this->dry_run = Utils\get_flag_value( $assoc_args, 'dry-run', false ); $php_only = Utils\get_flag_value( $assoc_args, 'precise', false ); $this->recurse_objects = Utils\get_flag_value( $assoc_args, 'recurse-objects', true ); + $this->recurse_keys = Utils\get_flag_value( $assoc_args, 'recurse-keys', false ); $this->verbose = Utils\get_flag_value( $assoc_args, 'verbose', false ); $this->format = Utils\get_flag_value( $assoc_args, 'format' ); $this->regex = Utils\get_flag_value( $assoc_args, 'regex', false ); @@ -642,7 +652,7 @@ private function php_export_table( $table, $old, $new ) { 'chunk_size' => $chunk_size, ); - $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, false, $this->regex_limit ); + $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, false, $this->regex_limit, $this->recurse_keys ); $col_counts = array_fill_keys( $all_columns, 0 ); if ( $this->verbose && 'table' === $this->format ) { $this->start_time = microtime( true ); @@ -747,7 +757,7 @@ private function php_handle_col( $col, $primary_keys, $table, $old, $new ) { global $wpdb; $count = 0; - $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, null !== $this->log_handle, $this->regex_limit ); + $replacer = new SearchReplacer( $old, $new, $this->recurse_objects, $this->regex, $this->regex_flags, $this->regex_delimiter, null !== $this->log_handle, $this->regex_limit, $this->recurse_keys ); $table_sql = self::esc_sql_ident( $table ); $col_sql = self::esc_sql_ident( $col ); diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 5e3ff77b..2b913890 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -32,6 +32,11 @@ class SearchReplacer { */ private $recurse_objects; + /** + * @var bool + */ + private $recurse_keys; + /** * @var bool */ @@ -81,11 +86,13 @@ class SearchReplacer { * @param string $regex_delimiter Delimiter for regular expression. * @param bool $logging Whether logging. * @param integer $regex_limit The maximum possible replacements for each pattern in each subject string. + * @param bool $recurse_keys Should array keys and object property names be recursively replaced? */ - public function __construct( $from, $to, $recurse_objects = false, $regex = false, $regex_flags = '', $regex_delimiter = '/', $logging = false, $regex_limit = -1 ) { + public function __construct( $from, $to, $recurse_objects = false, $regex = false, $regex_flags = '', $regex_delimiter = '/', $logging = false, $regex_limit = -1, $recurse_keys = false ) { $this->from = $from; $this->to = $to; $this->recurse_objects = $recurse_objects; + $this->recurse_keys = $recurse_keys; $this->regex = $regex; $this->regex_flags = $regex_flags; $this->regex_delimiter = $regex_delimiter; @@ -180,10 +187,17 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis if ( false !== $unserialized ) { $data = $this->run_recursively( $unserialized, true, $recursion_level + 1 ); } elseif ( is_array( $data ) ) { - $keys = array_keys( $data ); + $keys = array_keys( $data ); + $replaced = array(); foreach ( $keys as $key ) { - $data[ $key ] = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data ); + $value = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data ); + $new_key = $key; + if ( $this->recurse_keys && is_string( $key ) ) { + $new_key = $this->replace_string( $key ); + } + $replaced[ $new_key ] = $value; } + $data = $replaced; } elseif ( $this->recurse_objects && ( is_object( $data ) || $data instanceof \__PHP_Incomplete_Class ) ) { if ( $data instanceof \__PHP_Incomplete_Class ) { $array = new ArrayObject( $data ); @@ -196,12 +210,26 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } else { try { $is_array_access = $data instanceof \ArrayAccess; + $properties = array(); foreach ( $data as $key => $value ) { - $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); + $properties[ $key ] = $value; + } + foreach ( $properties as $key => $value ) { + $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); + $new_key = $key; + if ( $this->recurse_keys && is_string( $key ) ) { + $new_key = $this->replace_string( $key ); + } if ( $is_array_access ) { - $data[ $key ] = $value; + if ( $new_key !== $key ) { + unset( $data[ $key ] ); + } + $data[ $new_key ] = $value; } else { - $data->$key = $value; + if ( $new_key !== $key ) { + unset( $data->$key ); + } + $data->$new_key = $value; } } } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound @@ -220,34 +248,7 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } } } elseif ( is_string( $data ) ) { - if ( $this->logging ) { - $old_data = $data; - } - if ( $this->regex ) { - $search_regex = $this->regex_delimiter; - $search_regex .= $this->from; - $search_regex .= $this->regex_delimiter; - $search_regex .= $this->regex_flags; - - $result = preg_replace( $search_regex, $this->to, $data, $this->regex_limit ); - if ( null === $result || PREG_NO_ERROR !== preg_last_error() ) { - \WP_CLI::warning( - sprintf( - 'The provided regular expression threw a PCRE error - %s', - $this->preg_error_message( $result ) - ) - ); - } - $data = $result; - } else { - $data = str_replace( $this->from, $this->to, $data ); - if ( $this->from_json !== $this->from ) { - $data = str_replace( $this->from_json, $this->to_json, $data ); - } - } - if ( $this->logging && $old_data !== $data ) { - $this->log_data[] = $old_data; - } + $data = $this->replace_string( $data ); } if ( $serialised ) { @@ -260,6 +261,48 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis return $data; } + /** + * Replace occurrences of the search string within a single string. + * + * Used for values as well as array keys and object property names when + * key recursion is enabled. + * + * @param string $data The string to operate on. + * @return string The string with all replacements made as needed. + */ + private function replace_string( $data ) { + if ( $this->logging ) { + $old_data = $data; + } + if ( $this->regex ) { + $search_regex = $this->regex_delimiter; + $search_regex .= $this->from; + $search_regex .= $this->regex_delimiter; + $search_regex .= $this->regex_flags; + + $result = preg_replace( $search_regex, $this->to, $data, $this->regex_limit ); + if ( null === $result || PREG_NO_ERROR !== preg_last_error() ) { + \WP_CLI::warning( + sprintf( + 'The provided regular expression threw a PCRE error - %s', + $this->preg_error_message( $result ) + ) + ); + } + $data = $result; + } else { + $data = str_replace( $this->from, $this->to, $data ); + if ( $this->from_json !== $this->from ) { + $data = str_replace( $this->from_json, $this->to_json, $data ); + } + } + if ( $this->logging && $old_data !== $data ) { + $this->log_data[] = $old_data; + } + + return $data; + } + /** * Gets existing data saved for this run when logging. * @return string[] Array of data strings, prior to replacements. From 244e8959d9b5f2e5f54ab324973cd537a64cfc03 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:07:50 -0600 Subject: [PATCH 02/10] fix(search-replace): preserve references and skip on key collisions --- features/search-replace.feature | 109 +++++++++++++++++++++++ src/WP_CLI/SearchReplacer.php | 151 ++++++++++++++++++++++++++------ 2 files changed, 232 insertions(+), 28 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index ab408608..5d63a16c 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1714,3 +1714,112 @@ Feature: Do global search/replace """ old.example.com """ + + @require-mysql + Scenario: Refuse to rename colliding array keys with --recurse-keys + Given a WP install + And a setup-recurse-keys-collision.php file: + """ + 'v1', 'https://new.example.com/key' => 'v2' ), false ); + """ + And a check-recurse-keys-collision.php file: + """ + 'v1', 'https://new.example.com/prop' => 'v2' ), false ); + """ + And a check-recurse-keys-object-collision.php file: + """ + &$shared, 'b' => &$shared ), false ); + """ + And a check-recurse-keys-refs.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_ref_test'" ); + $value = get_option( 'recurse_keys_ref_test' ); + echo json_encode( $value, JSON_UNESCAPED_SLASHES ), "\n"; + echo false !== strpos( $raw, 'R:2;' ) ? 'HASREF' : 'NOREF'; + """ + And I run `wp eval-file setup-recurse-keys-refs.php` + + When I run `wp search-replace 'https://old.example.com' 'https://new.example.com' --recurse-keys` + Then STDOUT should contain: + """ + Success: + """ + + When I run `wp eval-file check-recurse-keys-refs.php` + Then STDOUT should contain: + """ + "https://new.example.com/a":"https://new.example.com/shared" + """ + And STDOUT should contain: + """ + HASREF + """ diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 2b913890..46e806cf 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -187,17 +187,14 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis if ( false !== $unserialized ) { $data = $this->run_recursively( $unserialized, true, $recursion_level + 1 ); } elseif ( is_array( $data ) ) { - $keys = array_keys( $data ); - $replaced = array(); - foreach ( $keys as $key ) { - $value = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data ); - $new_key = $key; - if ( $this->recurse_keys && is_string( $key ) ) { - $new_key = $this->replace_string( $key ); + if ( $this->recurse_keys ) { + $data = $this->replace_array_keys( $data, $recursion_level, $visited_data ); + } else { + $keys = array_keys( $data ); + foreach ( $keys as $key ) { + $data[ $key ] = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data ); } - $replaced[ $new_key ] = $value; } - $data = $replaced; } elseif ( $this->recurse_objects && ( is_object( $data ) || $data instanceof \__PHP_Incomplete_Class ) ) { if ( $data instanceof \__PHP_Incomplete_Class ) { $array = new ArrayObject( $data ); @@ -210,26 +207,16 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } else { try { $is_array_access = $data instanceof \ArrayAccess; - $properties = array(); - foreach ( $data as $key => $value ) { - $properties[ $key ] = $value; - } - foreach ( $properties as $key => $value ) { - $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); - $new_key = $key; - if ( $this->recurse_keys && is_string( $key ) ) { - $new_key = $this->replace_string( $key ); - } - if ( $is_array_access ) { - if ( $new_key !== $key ) { - unset( $data[ $key ] ); + if ( $this->recurse_keys ) { + $data = $this->replace_object_property_names( $data, $is_array_access, $recursion_level, $visited_data ); + } else { + foreach ( $data as $key => $value ) { + $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); + if ( $is_array_access ) { + $data[ $key ] = $value; + } else { + $data->$key = $value; } - $data[ $new_key ] = $value; - } else { - if ( $new_key !== $key ) { - unset( $data->$key ); - } - $data->$new_key = $value; } } } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound @@ -303,6 +290,114 @@ private function replace_string( $data ) { return $data; } + /** + * Recurse into an array, replacing string keys as well as values. + * + * Renamed keys keep their original position. Shared references between + * elements are preserved by iterating by reference. When two keys would + * map onto the same key, the array is left unchanged and a warning is + * emitted instead of silently discarding a value. + * + * @param array $data The array to process. + * @param int $recursion_level Current recursion depth. + * @param array $visited_data Previously seen arrays and objects. + * @return array The processed array. + */ + private function replace_array_keys( $data, $recursion_level, $visited_data ) { + $renames = array(); + foreach ( array_keys( $data ) as $key ) { + $renames[ $key ] = is_string( $key ) ? $this->replace_string( $key ) : $key; + } + if ( count( array_unique( $renames, SORT_REGULAR ) ) !== count( $renames ) ) { + \WP_CLI::warning( 'Skipping key replacement for an array: two keys would map onto the same key and a value would be lost.' ); + return $data; + } + $replaced = array(); + foreach ( $data as $key => &$value ) { + $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); + $replaced[ $renames[ $key ] ] =& $value; + } + unset( $value ); + return $replaced; + } + + /** + * Recurse into an object, replacing string property names as well as values. + * + * When two property names would map onto the same name, the object is + * left unchanged and a warning is emitted instead of silently + * discarding a value. + * + * @param object $data The object to process. + * @param bool $is_array_access Whether the object implements ArrayAccess. + * @param int $recursion_level Current recursion depth. + * @param array $visited_data Previously seen arrays and objects. + * @return object The processed object. + */ + private function replace_object_property_names( $data, $is_array_access, $recursion_level, $visited_data ) { + $renames = array(); + foreach ( $data as $key => $value ) { + $renames[ $key ] = is_string( $key ) ? $this->replace_string( $key ) : $key; + } + if ( count( array_unique( $renames, SORT_REGULAR ) ) !== count( $renames ) ) { + \WP_CLI::warning( 'Skipping key replacement for an object: two property names would map onto the same name and a value would be lost.' ); + return $data; + } + foreach ( $renames as $key => $new_key ) { + $value = $this->run_recursively( $this->read_property( $data, $is_array_access, $key ), false, $recursion_level + 1, $visited_data ); + if ( $new_key !== $key ) { + $this->remove_property( $data, $is_array_access, $key ); + } + $this->write_property( $data, $is_array_access, $new_key, $value ); + } + return $data; + } + + /** + * Read one property or offset from an object or ArrayAccess instance. + * + * @param object $data The object to read from. + * @param bool $is_array_access Whether the object implements ArrayAccess. + * @param string $key The property name or offset. + * @return mixed The property value. + */ + private function read_property( $data, $is_array_access, $key ) { + return $is_array_access ? $data[ $key ] : $data->$key; + } + + /** + * Remove one property or offset from an object or ArrayAccess instance. + * + * @param object $data The object to modify, by reference. + * @param bool $is_array_access Whether the object implements ArrayAccess. + * @param string $key The property name or offset. + * @return void + */ + private function remove_property( &$data, $is_array_access, $key ) { + if ( $is_array_access ) { + unset( $data[ $key ] ); + } else { + unset( $data->$key ); + } + } + + /** + * Write one property or offset on an object or ArrayAccess instance. + * + * @param object $data The object to modify, by reference. + * @param bool $is_array_access Whether the object implements ArrayAccess. + * @param string $key The property name or offset. + * @param mixed $value The value to write. + * @return void + */ + private function write_property( &$data, $is_array_access, $key, $value ) { + if ( $is_array_access ) { + $data[ $key ] = $value; + } else { + $data->$key = $value; + } + } + /** * Gets existing data saved for this run when logging. * @return string[] Array of data strings, prior to replacements. From 8797224679f34e871c5667a27d160b52c631c2b3 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 24 Nov 2026 13:21:08 +0000 Subject: [PATCH 03/10] Keep replacing values when key renames would collide When two keys (or property names) would map onto the same key, the array/object was returned untouched, so its values and nested data were skipped entirely, leaving more stale strings than running without --recurse-keys. Fall back to keeping the original keys while still recursing into the values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 12 ++++++++++-- src/WP_CLI/SearchReplacer.php | 14 +++++++------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index 5d63a16c..c02a820a 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1721,7 +1721,7 @@ Feature: Do global search/replace And a setup-recurse-keys-collision.php file: """ 'v1', 'https://new.example.com/key' => 'v2' ), false ); + update_option( 'recurse_keys_collision_test', array( 'https://old.example.com/key' => 'v1', 'https://new.example.com/key' => 'v2', 'other' => 'https://old.example.com/value' ), false ); """ And a check-recurse-keys-collision.php file: """ @@ -1751,6 +1751,10 @@ Feature: Do global search/replace """ "https://new.example.com/key":"v2" """ + And STDOUT should contain: + """ + "other":"https://new.example.com/value" + """ @require-mysql Scenario: Refuse to rename colliding object property names with --recurse-keys @@ -1758,7 +1762,7 @@ Feature: Do global search/replace And a setup-recurse-keys-object-collision.php file: """ 'v1', 'https://new.example.com/prop' => 'v2' ), false ); + update_option( 'recurse_keys_object_collision_test', (object) array( 'https://old.example.com/prop' => 'v1', 'https://new.example.com/prop' => 'v2', 'other' => 'https://old.example.com/value' ), false ); """ And a check-recurse-keys-object-collision.php file: """ @@ -1788,6 +1792,10 @@ Feature: Do global search/replace """ "https://new.example.com/prop":"v2" """ + And STDOUT should contain: + """ + "other":"https://new.example.com/value" + """ @require-mysql Scenario: Preserve shared references when renaming keys with --recurse-keys diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 46e806cf..7dd275df 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -295,8 +295,8 @@ private function replace_string( $data ) { * * Renamed keys keep their original position. Shared references between * elements are preserved by iterating by reference. When two keys would - * map onto the same key, the array is left unchanged and a warning is - * emitted instead of silently discarding a value. + * map onto the same key, the keys are left unchanged (values are still + * replaced) and a warning is emitted instead of silently discarding a value. * * @param array $data The array to process. * @param int $recursion_level Current recursion depth. @@ -310,7 +310,7 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { } if ( count( array_unique( $renames, SORT_REGULAR ) ) !== count( $renames ) ) { \WP_CLI::warning( 'Skipping key replacement for an array: two keys would map onto the same key and a value would be lost.' ); - return $data; + $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } $replaced = array(); foreach ( $data as $key => &$value ) { @@ -324,9 +324,9 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { /** * Recurse into an object, replacing string property names as well as values. * - * When two property names would map onto the same name, the object is - * left unchanged and a warning is emitted instead of silently - * discarding a value. + * When two property names would map onto the same name, the property + * names are left unchanged (values are still replaced) and a warning is + * emitted instead of silently discarding a value. * * @param object $data The object to process. * @param bool $is_array_access Whether the object implements ArrayAccess. @@ -341,7 +341,7 @@ private function replace_object_property_names( $data, $is_array_access, $recurs } if ( count( array_unique( $renames, SORT_REGULAR ) ) !== count( $renames ) ) { \WP_CLI::warning( 'Skipping key replacement for an object: two property names would map onto the same name and a value would be lost.' ); - return $data; + $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } foreach ( $renames as $key => $new_key ) { $value = $this->run_recursively( $this->read_property( $data, $is_array_access, $key ), false, $recursion_level + 1, $visited_data ); From 002673efe1910d23be0fa11587e5c26ae525844e Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 24 Nov 2026 15:21:40 +0000 Subject: [PATCH 04/10] Harden --recurse-keys collision checks and stage object renames - Detect destination-key collisions by PHP array-key storage identity instead of array_unique( SORT_REGULAR ), so distinct keys such as 8 and '08' no longer trigger the collision fallback. - Compare offsets case-insensitively for the Requests case-insensitive dictionary, and keep the original offsets for ArrayAccess implementations whose offset semantics are unknown. - Read and process all property values before removing or writing any property, so overlapping source/destination names cannot lose data. - Add Behat scenarios for all three cases. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 83 +++++++++++++++++++++++++++++++++ src/WP_CLI/SearchReplacer.php | 81 +++++++++++++++++++++++++++++--- 2 files changed, 157 insertions(+), 7 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index c02a820a..dd3dd0c7 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1831,3 +1831,86 @@ Feature: Do global search/replace """ HASREF """ + + Scenario: Key collision detection with --recurse-keys compares keys as PHP stores them + Given a WP install + And a recurse-keys-storage-identity.php file: + """ + run( serialize( array( 8 => 'v1', '08' => 'v2', 'old' => 'v3' ) ) ), "\n"; + echo $replacer->run( serialize( (object) array( 8 => 'v1', '08' => 'v2', 'old' => 'v3' ) ) ), "\n"; + """ + + When I run `wp eval-file recurse-keys-storage-identity.php` + Then STDERR should be empty + And STDOUT should contain: + """ + a:3:{i:8;s:2:"v1";s:2:"08";s:2:"v2";s:3:"new";s:2:"v3";} + """ + And STDOUT should contain: + """ + s:3:"new";s:2:"v3";} + """ + And STDOUT should not contain: + """ + "old" + """ + + Scenario: Overlapping property names are renamed without losing values with --recurse-keys + Given a WP install + And a recurse-keys-overlap.php file: + """ + run( serialize( (object) array( 'old' => 'v1', 'newold' => 'v2' ) ) ) ); + echo json_encode( $result ); + """ + + When I run `wp eval-file recurse-keys-overlap.php` + Then STDERR should be empty + And STDOUT should contain: + """ + "newold":"v1" + """ + And STDOUT should contain: + """ + "newnewold":"v2" + """ + + # `CaseInsensitiveDictionary` is from Requests 2.0, which was added in 6.2. + @require-wp-6.2 + Scenario: Case-insensitive dictionary offsets are not renamed onto an existing offset with --recurse-keys + Given a WP install + And a recurse-keys-case-insensitive.php file: + """ + [ 'WpOrg\Requests\Utility\CaseInsensitiveDictionary' ] ]; + } + ); + $replacer = new \WP_CLI\SearchReplacer( 'old', 'NEW', true, false, '', '/', false, -1, true ); + $result = unserialize( + $replacer->run( + serialize( new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( [ 'old' => 'v1', 'new' => 'v2' ] ) ) + ), + [ 'allowed_classes' => [ 'WpOrg\Requests\Utility\CaseInsensitiveDictionary' ] ] + ); + echo json_encode( $result->getAll() ); + """ + + When I try `wp eval-file recurse-keys-case-insensitive.php` + Then STDERR should contain: + """ + two property names would map onto the same name + """ + And STDOUT should contain: + """ + "old":"v1" + """ + And STDOUT should contain: + """ + "new":"v2" + """ diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 7dd275df..6de41c4f 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -308,7 +308,7 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { foreach ( array_keys( $data ) as $key ) { $renames[ $key ] = is_string( $key ) ? $this->replace_string( $key ) : $key; } - if ( count( array_unique( $renames, SORT_REGULAR ) ) !== count( $renames ) ) { + if ( $this->has_destination_collision( $renames, false ) ) { \WP_CLI::warning( 'Skipping key replacement for an array: two keys would map onto the same key and a value would be lost.' ); $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } @@ -324,9 +324,17 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { /** * Recurse into an object, replacing string property names as well as values. * - * When two property names would map onto the same name, the property - * names are left unchanged (values are still replaced) and a warning is - * emitted instead of silently discarding a value. + * All values are read and processed before the object is modified, so a + * renamed property can never overwrite a source property that has not + * been read yet. When two property names would map onto the same name, + * the property names are left unchanged (values are still replaced) and a + * warning is emitted instead of silently discarding a value. + * + * ArrayAccess implementations may normalize offsets on write. Offsets are + * only renamed for implementations whose offset semantics are known + * (ArrayObject, ArrayIterator and the Requests case-insensitive + * dictionary); for any other ArrayAccess implementation the original + * offsets are kept. * * @param object $data The object to process. * @param bool $is_array_access Whether the object implements ArrayAccess. @@ -339,20 +347,79 @@ private function replace_object_property_names( $data, $is_array_access, $recurs foreach ( $data as $key => $value ) { $renames[ $key ] = is_string( $key ) ? $this->replace_string( $key ) : $key; } - if ( count( array_unique( $renames, SORT_REGULAR ) ) !== count( $renames ) ) { + + $case_insensitive = false; + $keep_offsets = false; + if ( $is_array_access ) { + if ( $data instanceof \WpOrg\Requests\Utility\CaseInsensitiveDictionary || is_a( $data, 'Requests_Utility_CaseInsensitiveDictionary' ) ) { + $case_insensitive = true; + } elseif ( ! $data instanceof \ArrayObject && ! $data instanceof \ArrayIterator ) { + $keep_offsets = true; + } + } + + $renamed = false; + foreach ( $renames as $key => $new_key ) { + if ( $new_key !== $key ) { + $renamed = true; + break; + } + } + + if ( $renamed && $keep_offsets ) { + \WP_CLI::warning( + sprintf( + 'Skipping key replacement for an object of class "%s": its offset semantics are unknown.', + get_class( $data ) + ) + ); + $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); + } elseif ( $renamed && $this->has_destination_collision( $renames, $case_insensitive ) ) { \WP_CLI::warning( 'Skipping key replacement for an object: two property names would map onto the same name and a value would be lost.' ); $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } + + // Stage all processed values before touching the object. + $values = array(); + foreach ( $renames as $key => $new_key ) { + $values[ $key ] = $this->run_recursively( $this->read_property( $data, $is_array_access, $key ), false, $recursion_level + 1, $visited_data ); + } foreach ( $renames as $key => $new_key ) { - $value = $this->run_recursively( $this->read_property( $data, $is_array_access, $key ), false, $recursion_level + 1, $visited_data ); if ( $new_key !== $key ) { $this->remove_property( $data, $is_array_access, $key ); } - $this->write_property( $data, $is_array_access, $new_key, $value ); + } + foreach ( $renames as $key => $new_key ) { + $this->write_property( $data, $is_array_access, $new_key, $values[ $key ] ); } return $data; } + /** + * Check whether two renamed keys would end up as the same stored key. + * + * Destination keys are compared by how PHP actually stores them as array + * keys (so `8` and `'08'` stay distinct, while `'8'` and `8` collide), and + * optionally case-insensitively for containers that normalize offsets. + * + * @param array $renames Map of original key to destination key. + * @param bool $case_insensitive Whether destination keys are compared case-insensitively. + * @return bool Whether at least two destination keys collide. + */ + private function has_destination_collision( $renames, $case_insensitive ) { + $seen = array(); + foreach ( $renames as $new_key ) { + if ( $case_insensitive && is_string( $new_key ) ) { + $new_key = strtolower( $new_key ); + } + if ( isset( $seen[ $new_key ] ) ) { + return true; + } + $seen[ $new_key ] = true; + } + return false; + } + /** * Read one property or offset from an object or ArrayAccess instance. * From baabf9b6b91d73dffcbf096441a04ed6da766947 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 24 Nov 2026 15:31:15 +0000 Subject: [PATCH 05/10] Put array items on their own lines in the new recurse-keys scenarios Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index dd3dd0c7..0c6a2758 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1838,8 +1838,13 @@ Feature: Do global search/replace """ run( serialize( array( 8 => 'v1', '08' => 'v2', 'old' => 'v3' ) ) ), "\n"; - echo $replacer->run( serialize( (object) array( 8 => 'v1', '08' => 'v2', 'old' => 'v3' ) ) ), "\n"; + $data = array( + 8 => 'v1', + '08' => 'v2', + 'old' => 'v3', + ); + echo $replacer->run( serialize( $data ) ), "\n"; + echo $replacer->run( serialize( (object) $data ) ), "\n"; """ When I run `wp eval-file recurse-keys-storage-identity.php` @@ -1863,7 +1868,11 @@ Feature: Do global search/replace """ run( serialize( (object) array( 'old' => 'v1', 'newold' => 'v2' ) ) ) ); + $data = array( + 'old' => 'v1', + 'newold' => 'v2', + ); + $result = unserialize( $replacer->run( serialize( (object) $data ) ) ); echo json_encode( $result ); """ @@ -1894,7 +1903,14 @@ Feature: Do global search/replace $replacer = new \WP_CLI\SearchReplacer( 'old', 'NEW', true, false, '', '/', false, -1, true ); $result = unserialize( $replacer->run( - serialize( new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( [ 'old' => 'v1', 'new' => 'v2' ] ) ) + serialize( + new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( + [ + 'old' => 'v1', + 'new' => 'v2', + ] + ) + ) ), [ 'allowed_classes' => [ 'WpOrg\Requests\Utility\CaseInsensitiveDictionary' ] ] ); From 04a944efeb0d70ec5967c64239a1700bb3e58418 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 11:09:27 +0000 Subject: [PATCH 06/10] Keep the original key when a --recurse-keys regex replacement fails On a PCRE error preg_replace() returns null, which was used as the new array key and silently turned the key into an empty string. Keep the original key in that case, matching the warning that is already shown. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 27 +++++++++++++++++++++++++++ src/WP_CLI/SearchReplacer.php | 22 ++++++++++++++++++++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index 91c79b3e..bac8c166 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1976,3 +1976,30 @@ Feature: Do global search/replace """ "new":"v2" """ + + @require-mysql + Scenario: Keep the original key when a regex replacement fails with --recurse-keys + Given a WP install + And a setup-recurse-keys-pcre.php file: + """ + 'keep!' ) ); + """ + And a check-recurse-keys-pcre.php file: + """ + replace_string( $key ); + return is_string( $new_key ) ? $new_key : $key; + } + /** * Recurse into an array, replacing string keys as well as values. * @@ -306,7 +324,7 @@ private function replace_string( $data ) { private function replace_array_keys( $data, $recursion_level, $visited_data ) { $renames = array(); foreach ( array_keys( $data ) as $key ) { - $renames[ $key ] = is_string( $key ) ? $this->replace_string( $key ) : $key; + $renames[ $key ] = $this->replace_key( $key ); } if ( $this->has_destination_collision( $renames, false ) ) { \WP_CLI::warning( 'Skipping key replacement for an array: two keys would map onto the same key and a value would be lost.' ); @@ -345,7 +363,7 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { private function replace_object_property_names( $data, $is_array_access, $recursion_level, $visited_data ) { $renames = array(); foreach ( $data as $key => $value ) { - $renames[ $key ] = is_string( $key ) ? $this->replace_string( $key ) : $key; + $renames[ $key ] = $this->replace_key( $key ); } $case_insensitive = false; From 7a81682268514f00231e3bd4169c1297d9b0a15d Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 16:14:50 +0000 Subject: [PATCH 07/10] Make --recurse-keys object renames safe for readonly properties, references and logs - Never rename a readonly property (PHP 8.1+) or rename onto one; keep that name and still replace the other names and values. If modifying an object fails part way anyway, restore its original property names and values before passing the error on, so a partly renamed object is never saved. - Rename object properties by reference, so properties that share a PHP reference keep sharing it. - With --log, record key replacements only once the container accepts the renames; rejected renames (collision, unknown offset semantics, readonly) are no longer logged as applied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 124 ++++++++++++++++++++++ src/WP_CLI/SearchReplacer.php | 178 +++++++++++++++++++++++++++++--- 2 files changed, 288 insertions(+), 14 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index bac8c166..8e1c2c99 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -2003,3 +2003,127 @@ Feature: Do global search/replace """ {"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!":"keep!"} """ + + @require-mysql + Scenario: Do not log rejected key renames with --recurse-keys --log + Given a WP install + And a setup-recurse-keys-log.php file: + """ + 'v1', 'newtok/key' => 'v2', 'other' => 'oldtok/value' ), false ); + """ + And I run `wp eval-file setup-recurse-keys-log.php` + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys --log` + Then STDERR should contain: + """ + two keys would map onto the same key + """ + And STDOUT should contain: + """ + < oldtok/value + """ + And STDOUT should contain: + """ + > newtok/value + """ + And STDOUT should not contain: + """ + oldtok/key + """ + + @require-mysql @require-php-8.1 + Scenario: Keep readonly property names and all values when renaming property names with --recurse-keys + Given a WP install + And a wp-content/mu-plugins/recurse-keys-readonly.php file: + """ + oldtok_mutable = $mutable; + $this->oldtok_ro = $ro; + } + } + if ( class_exists( 'WP_CLI' ) ) { + WP_CLI::add_hook( + 'search_replace_unserialize_options', + function () { + return [ 'allowed_classes' => [ 'stdClass', 'Recurse_Keys_Readonly_Test' ] ]; + } + ); + } + """ + And a setup-recurse-keys-readonly.php file: + """ + new Recurse_Keys_Readonly_Test( 'keep-mutable', 'keep-ro' ) ), false ); + """ + And a check-recurse-keys-readonly.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_readonly_test'" ); + """ + And I run `wp eval-file setup-recurse-keys-readonly.php` + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then the return code should be 0 + + When I run `wp eval-file check-recurse-keys-readonly.php` + Then STDOUT should contain: + """ + s:9:"oldtok_ro";s:7:"keep-ro"; + """ + And STDOUT should contain: + """ + s:12:"keep-mutable"; + """ + + @require-mysql + Scenario: Preserve shared object property references when renaming property names with --recurse-keys + Given a WP install + And a setup-recurse-keys-object-refs.php file: + """ + {'oldtok/a'} = 'shared'; + $object->b = &$object->{'oldtok/a'}; + update_option( 'recurse_keys_object_ref_test', array( 'item' => $object ), false ); + """ + And a check-recurse-keys-object-refs.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_object_ref_test'" ); + echo $raw, "\n"; + echo preg_match( '/[Rr]:\d+;/', $raw ) ? 'HASREF' : 'NOREF', "\n"; + $value = get_option( 'recurse_keys_object_ref_test' ); + $value['item']->b = 'changed'; + echo $value['item']->{'newtok/a'}; + """ + And I run `wp eval-file setup-recurse-keys-object-refs.php` + + When I run `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then STDOUT should contain: + """ + Success: + """ + + When I run `wp eval-file check-recurse-keys-object-refs.php` + Then STDOUT should contain: + """ + s:8:"newtok/a"; + """ + And STDOUT should contain: + """ + "shared" + """ + And STDOUT should contain: + """ + HASREF + """ + And STDOUT should contain: + """ + changed + """ diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index 569a22ac..ba1caf9e 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -308,6 +308,48 @@ private function replace_key( $key ) { return is_string( $new_key ) ? $new_key : $key; } + /** + * Work out the replacement for each key of a container. + * + * Log entries produced while replacing the keys are kept apart from the + * value log, so that they can be committed only once the container + * accepts the renames (see commit_key_logs()). + * + * @param array $keys The keys or property names. + * @return array{0: array, 1: array} Map of original key to + * destination key, and the pending log entries for each key. + */ + private function plan_key_renames( $keys ) { + $renames = array(); + $key_logs = array(); + foreach ( $keys as $key ) { + $mark = count( $this->log_data ); + $renames[ $key ] = $this->replace_key( $key ); + $key_logs[ $key ] = array_splice( $this->log_data, $mark ); + } + return array( $renames, $key_logs ); + } + + /** + * Add the log entries of the keys that were actually renamed. + * + * @param array $renames Map of original key to destination key. + * @param array $key_logs Pending log entries for each key. + * @param int $position Position in the log at which to insert the entries. + * @return void + */ + private function commit_key_logs( $renames, $key_logs, $position ) { + $accepted = array(); + foreach ( $renames as $key => $new_key ) { + if ( $new_key !== $key ) { + $accepted = array_merge( $accepted, $key_logs[ $key ] ); + } + } + if ( $accepted ) { + array_splice( $this->log_data, $position, 0, $accepted ); + } + } + /** * Recurse into an array, replacing string keys as well as values. * @@ -322,20 +364,19 @@ private function replace_key( $key ) { * @return array The processed array. */ private function replace_array_keys( $data, $recursion_level, $visited_data ) { - $renames = array(); - foreach ( array_keys( $data ) as $key ) { - $renames[ $key ] = $this->replace_key( $key ); - } + list( $renames, $key_logs ) = $this->plan_key_renames( array_keys( $data ) ); if ( $this->has_destination_collision( $renames, false ) ) { \WP_CLI::warning( 'Skipping key replacement for an array: two keys would map onto the same key and a value would be lost.' ); $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } - $replaced = array(); + $log_position = count( $this->log_data ); + $replaced = array(); foreach ( $data as $key => &$value ) { $value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data ); $replaced[ $renames[ $key ] ] =& $value; } unset( $value ); + $this->commit_key_logs( $renames, $key_logs, $log_position ); return $replaced; } @@ -348,6 +389,12 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { * the property names are left unchanged (values are still replaced) and a * warning is emitted instead of silently discarding a value. * + * Readonly properties (PHP 8.1+) are never renamed, and no property is + * renamed onto a readonly property. Properties that share a PHP reference + * keep sharing it after a rename. If modifying the object fails part way, + * it is restored to its original property names and values before the + * error is passed on. + * * ArrayAccess implementations may normalize offsets on write. Offsets are * only renamed for implementations whose offset semantics are known * (ArrayObject, ArrayIterator and the Requests case-insensitive @@ -361,10 +408,11 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { * @return object The processed object. */ private function replace_object_property_names( $data, $is_array_access, $recursion_level, $visited_data ) { - $renames = array(); + $keys = array(); foreach ( $data as $key => $value ) { - $renames[ $key ] = $this->replace_key( $key ); + $keys[] = $key; } + list( $renames, $key_logs ) = $this->plan_key_renames( $keys ); $case_insensitive = false; $keep_offsets = false; @@ -376,6 +424,20 @@ private function replace_object_property_names( $data, $is_array_access, $recurs } } + $readonly = $is_array_access ? array() : $this->get_readonly_property_names( $data ); + foreach ( $renames as $key => $new_key ) { + if ( $new_key !== $key && ( isset( $readonly[ $key ] ) || isset( $readonly[ $new_key ] ) ) ) { + \WP_CLI::warning( + sprintf( + 'Skipping key replacement for property "%s" of an object of class "%s": a readonly property cannot be renamed or overwritten.', + $key, + get_class( $data ) + ) + ); + $renames[ $key ] = $key; + } + } + $renamed = false; foreach ( $renames as $key => $new_key ) { if ( $new_key !== $key ) { @@ -397,20 +459,108 @@ private function replace_object_property_names( $data, $is_array_access, $recurs $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } - // Stage all processed values before touching the object. - $values = array(); + // Take a reference to each writable property, so that renaming a + // property keeps any reference it shares with other properties. + $refs = array(); + $originals = array(); foreach ( $renames as $key => $new_key ) { - $values[ $key ] = $this->run_recursively( $this->read_property( $data, $is_array_access, $key ), false, $recursion_level + 1, $visited_data ); + if ( $is_array_access || isset( $readonly[ $key ] ) ) { + $originals[ $key ] = $this->read_property( $data, $is_array_access, $key ); + } else { + $refs[ $key ] = &$data->$key; + $originals[ $key ] = $refs[ $key ]; + } } + + // Stage all processed values before touching the object. + $log_position = count( $this->log_data ); + $values = array(); foreach ( $renames as $key => $new_key ) { - if ( $new_key !== $key ) { - $this->remove_property( $data, $is_array_access, $key ); + $values[ $key ] = $this->run_recursively( $originals[ $key ], false, $recursion_level + 1, $visited_data ); + } + + $removed = array(); + $written = array(); + try { + foreach ( $renames as $key => $new_key ) { + if ( $new_key !== $key ) { + $this->remove_property( $data, $is_array_access, $key ); + $removed[ $key ] = true; + } + } + foreach ( $renames as $key => $new_key ) { + if ( isset( $readonly[ $key ] ) ) { + if ( $values[ $key ] !== $originals[ $key ] ) { + throw new \Error( sprintf( 'Cannot modify readonly property %s::$%s', get_class( $data ), $key ) ); // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound + } + continue; + } + if ( $is_array_access ) { + $this->write_property( $data, true, $new_key, $values[ $key ] ); + if ( $new_key !== $key ) { + $written[] = $new_key; + } + continue; + } + if ( $new_key !== $key ) { + $data->$new_key = &$refs[ $key ]; + $written[] = $new_key; + } + $refs[ $key ] = $values[ $key ]; } + } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound + $this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written ); + throw $exception; + } + + $this->commit_key_logs( $renames, $key_logs, $log_position ); + return $data; + } + + /** + * Restore an object to its original property names and values after a failed modification. + * + * @param object $data The object to restore. + * @param bool $is_array_access Whether the object implements ArrayAccess. + * @param array $renames Map of original key to destination key. + * @param array $originals Original values, by original key. + * @param array $refs References to the original properties, by original key. + * @param array $removed Original keys that were removed. + * @param array $written Destination keys that were written. + * @return void + */ + private function restore_object( $data, $is_array_access, $renames, $originals, &$refs, $removed, $written ) { + foreach ( $written as $name ) { + $this->remove_property( $data, $is_array_access, $name ); } foreach ( $renames as $key => $new_key ) { - $this->write_property( $data, $is_array_access, $new_key, $values[ $key ] ); + if ( $is_array_access ) { + $this->write_property( $data, true, $key, $originals[ $key ] ); + } elseif ( array_key_exists( $key, $refs ) ) { + if ( isset( $removed[ $key ] ) ) { + $data->$key = &$refs[ $key ]; + } + $refs[ $key ] = $originals[ $key ]; + } } - return $data; + } + + /** + * Get the names of the readonly properties of an object. + * + * Readonly properties exist as of PHP 8.1; on older versions there are none. + * + * @param object $data The object to inspect. + * @return array Readonly property names as keys. + */ + private function get_readonly_property_names( $data ) { + $names = array(); + foreach ( ( new \ReflectionObject( $data ) )->getProperties() as $property ) { + if ( method_exists( $property, 'isReadOnly' ) && $property->isReadOnly() ) { + $names[ $property->getName() ] = true; + } + } + return $names; } /** From 2e533fb3f043a00532cb83a1225c7f5bf3db5ca8 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 16:45:18 +0000 Subject: [PATCH 08/10] Harden --recurse-keys object property renames - Compare object property names as strings, so an unchanged numeric property name such as "8" is no longer removed and re-added (which reordered the object and changed the stored value even without a match). - Restore the object on Exception as well as Error, e.g. when an allowed ArrayObject subclass throws from offsetUnset() after an earlier removal, and restore the original order of the remaining properties/offsets. - Bind references only for renamed properties; read and assign properties that keep their name normally, so PHP 8.4 set hooks still apply. - Move only the log entries appended for each key instead of rebuilding the whole log with array_splice() per key. - Assert that the writable property is actually renamed in the readonly scenario, and add regression scenarios for the numeric property order and the exception restore. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 95 ++++++++++++++++++++++++++++++++- src/WP_CLI/SearchReplacer.php | 90 ++++++++++++++++++++++++------- 2 files changed, 166 insertions(+), 19 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index 8e1c2c99..9106cdf6 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -2078,7 +2078,11 @@ Feature: Do global search/replace """ And STDOUT should contain: """ - s:12:"keep-mutable"; + s:14:"newtok_mutable";s:12:"keep-mutable"; + """ + And STDOUT should not contain: + """ + "oldtok_mutable" """ @require-mysql @@ -2127,3 +2131,92 @@ Feature: Do global search/replace """ changed """ + + @require-mysql + Scenario: Keep the order of numeric object property names that are not renamed with --recurse-keys + Given a WP install + And a setup-recurse-keys-numeric-property.php file: + """ + {'8'} = 'top'; + $object->label = 'keep'; + update_option( 'recurse_keys_numeric_property_test', array( 'item' => $object, 'other' => 'oldtok' ), false ); + """ + And a check-recurse-keys-numeric-property.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_numeric_property_test'" ); + """ + And I run `wp eval-file setup-recurse-keys-numeric-property.php` + + When I run `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then STDOUT should contain: + """ + Success: + """ + + When I run `wp eval-file check-recurse-keys-numeric-property.php` + Then STDOUT should be: + """ + a:2:{s:4:"item";O:8:"stdClass":2:{s:1:"8";s:3:"top";s:5:"label";s:4:"keep";}s:5:"other";s:6:"newtok";} + """ + + When I run `wp search-replace 'stdClass' 'otherClass' wp_options --include-columns=option_value --recurse-keys --dry-run --report-changed-only` + Then STDOUT should not contain: + """ + wp_options + """ + + @require-mysql + Scenario: Restore an object when removing a property throws an exception with --recurse-keys + Given a WP install + And a wp-content/mu-plugins/recurse-keys-throwing-unset.php file: + """ + [ 'stdClass', 'Recurse_Keys_Throwing_Unset_Test' ] ]; + } + ); + } + """ + And a setup-recurse-keys-throwing-unset.php file: + """ + 'value-a', 'keep' => 'value-keep', 'oldtok_b' => 'value-b' ) ); + update_option( 'recurse_keys_throwing_unset_test', array( 'item' => $object ), false ); + echo $GLOBALS['wpdb']->get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_throwing_unset_test'" ); + """ + And a check-recurse-keys-throwing-unset.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_throwing_unset_test'" ); + """ + And I run `wp eval-file setup-recurse-keys-throwing-unset.php` + And save STDOUT as {ORIGINAL} + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then the return code should be 0 + + When I run `wp eval-file check-recurse-keys-throwing-unset.php` + Then STDOUT should be: + """ + {ORIGINAL} + """ + And STDOUT should contain: + """ + s:8:"oldtok_a";s:7:"value-a";s:4:"keep";s:10:"value-keep";s:8:"oldtok_b";s:7:"value-b"; + """ diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index ba1caf9e..c16b5adb 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -323,9 +323,16 @@ private function plan_key_renames( $keys ) { $renames = array(); $key_logs = array(); foreach ( $keys as $key ) { - $mark = count( $this->log_data ); - $renames[ $key ] = $this->replace_key( $key ); - $key_logs[ $key ] = array_splice( $this->log_data, $mark ); + $mark = count( $this->log_data ); + $renames[ $key ] = $this->replace_key( $key ); + // Move only the entries appended for this key out of the value log, + // instead of rebuilding the whole log for every key. + $pending = array(); + $appended = count( $this->log_data ) - $mark; + for ( $i = 0; $i < $appended; $i++ ) { + $pending[] = array_pop( $this->log_data ); + } + $key_logs[ $key ] = array_reverse( $pending ); } return array( $renames, $key_logs ); } @@ -342,7 +349,9 @@ private function commit_key_logs( $renames, $key_logs, $position ) { $accepted = array(); foreach ( $renames as $key => $new_key ) { if ( $new_key !== $key ) { - $accepted = array_merge( $accepted, $key_logs[ $key ] ); + foreach ( $key_logs[ $key ] as $entry ) { + $accepted[] = $entry; + } } } if ( $accepted ) { @@ -414,6 +423,17 @@ private function replace_object_property_names( $data, $is_array_access, $recurs } list( $renames, $key_logs ) = $this->plan_key_renames( $keys ); + if ( ! $is_array_access ) { + // Property names are always strings, but as keys of $renames numeric + // names such as "8" become integers. Compare them as strings, so that + // an unchanged numeric property name is not treated as renamed. + foreach ( $renames as $key => $new_key ) { + if ( (string) $new_key === (string) $key ) { + $renames[ $key ] = $key; + } + } + } + $case_insensitive = false; $keep_offsets = false; if ( $is_array_access ) { @@ -459,16 +479,18 @@ private function replace_object_property_names( $data, $is_array_access, $recurs $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } - // Take a reference to each writable property, so that renaming a - // property keeps any reference it shares with other properties. + // Take a reference to each property that is renamed, so that it keeps + // any reference it shares with other properties. Properties that keep + // their name are read and assigned normally, so that, for example, + // PHP 8.4 `set` hooks still apply to them. $refs = array(); $originals = array(); foreach ( $renames as $key => $new_key ) { - if ( $is_array_access || isset( $readonly[ $key ] ) ) { - $originals[ $key ] = $this->read_property( $data, $is_array_access, $key ); - } else { + if ( ! $is_array_access && $new_key !== $key ) { $refs[ $key ] = &$data->$key; $originals[ $key ] = $refs[ $key ]; + } else { + $originals[ $key ] = $this->read_property( $data, $is_array_access, $key ); } } @@ -479,8 +501,9 @@ private function replace_object_property_names( $data, $is_array_access, $recurs $values[ $key ] = $this->run_recursively( $originals[ $key ], false, $recursion_level + 1, $visited_data ); } - $removed = array(); - $written = array(); + $removed = array(); + $written = array(); + $assigned = array(); try { foreach ( $renames as $key => $new_key ) { if ( $new_key !== $key ) { @@ -505,11 +528,19 @@ private function replace_object_property_names( $data, $is_array_access, $recurs if ( $new_key !== $key ) { $data->$new_key = &$refs[ $key ]; $written[] = $new_key; + $refs[ $key ] = $values[ $key ]; + } else { + $data->$key = $values[ $key ]; + $assigned[ $key ] = true; } - $refs[ $key ] = $values[ $key ]; } } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound - $this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written ); + $this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written, $assigned ); + throw $exception; + } catch ( Exception $exception ) { + // ArrayAccess implementations may throw any exception, for example + // from offsetUnset() after an earlier offset was already removed. + $this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written, $assigned ); throw $exception; } @@ -520,6 +551,11 @@ private function replace_object_property_names( $data, $is_array_access, $recurs /** * Restore an object to its original property names and values after a failed modification. * + * Removed properties and offsets are added back at the end, so the + * properties and offsets that followed the first removed one are moved + * to the end as well, to restore the original order. Declared properties + * keep their position anyway and are not moved. + * * @param object $data The object to restore. * @param bool $is_array_access Whether the object implements ArrayAccess. * @param array $renames Map of original key to destination key. @@ -527,20 +563,38 @@ private function replace_object_property_names( $data, $is_array_access, $recurs * @param array $refs References to the original properties, by original key. * @param array $removed Original keys that were removed. * @param array $written Destination keys that were written. + * @param array $assigned Original keys that kept their name and were assigned. * @return void */ - private function restore_object( $data, $is_array_access, $renames, $originals, &$refs, $removed, $written ) { + private function restore_object( $data, $is_array_access, $renames, $originals, &$refs, $removed, $written, $assigned ) { foreach ( $written as $name ) { $this->remove_property( $data, $is_array_access, $name ); } + $class = get_class( $data ); + $move = false; foreach ( $renames as $key => $new_key ) { + if ( isset( $removed[ $key ] ) ) { + $move = true; + } if ( $is_array_access ) { - $this->write_property( $data, true, $key, $originals[ $key ] ); - } elseif ( array_key_exists( $key, $refs ) ) { - if ( isset( $removed[ $key ] ) ) { - $data->$key = &$refs[ $key ]; + if ( $move && ! isset( $removed[ $key ] ) ) { + $this->remove_property( $data, true, $key ); } + $this->write_property( $data, true, $key, $originals[ $key ] ); + } elseif ( isset( $removed[ $key ] ) ) { + $data->$key = &$refs[ $key ]; $refs[ $key ] = $originals[ $key ]; + } elseif ( $move && ! property_exists( $class, (string) $key ) ) { + // Move a dynamic property to the end, keeping any reference it shares. + $ref = &$data->$key; + unset( $data->$key ); + $data->$key = &$ref; + if ( isset( $assigned[ $key ] ) ) { + $ref = $originals[ $key ]; + } + unset( $ref ); + } elseif ( isset( $assigned[ $key ] ) ) { + $data->$key = $originals[ $key ]; } } } From 4c8da6ce0aa23e163b42fe5c42cc4cffd6c5cb12 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 17:10:28 +0000 Subject: [PATCH 09/10] Leave the whole value unchanged when a --recurse-keys rename fails With --recurse-keys, renaming keys or property names is now all or nothing per value: if reading, staging, removing or writing a property or offset throws (an Error or any Exception, at any nesting level), run() returns the original value unchanged, so the cell is neither updated nor counted, and the log entries collected for it are discarded. This replaces the best-effort rollback in restore_object(), which could stop part way (for example when an ArrayAccess implementation throws again during rollback, or rejects an immutable offset) and could not undo renames already made in nested objects, letting a partly modified value be saved. Without --recurse-keys nothing changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/search-replace.feature | 222 +++++++++++++++++++++++++++++++- src/WP_CLI/SearchReplacer.php | 177 +++++++++++++------------ 2 files changed, 307 insertions(+), 92 deletions(-) diff --git a/features/search-replace.feature b/features/search-replace.feature index 9106cdf6..5fa01dc1 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -2169,7 +2169,7 @@ Feature: Do global search/replace """ @require-mysql - Scenario: Restore an object when removing a property throws an exception with --recurse-keys + Scenario: Leave the stored value unchanged when removing a property throws an exception with --recurse-keys Given a WP install And a wp-content/mu-plugins/recurse-keys-throwing-unset.php file: """ @@ -2220,3 +2220,223 @@ Feature: Do global search/replace """ s:8:"oldtok_a";s:7:"value-a";s:4:"keep";s:10:"value-keep";s:8:"oldtok_b";s:7:"value-b"; """ + + @require-mysql + Scenario: Leave the stored value unchanged when an immutable offset sits between renamed offsets with --recurse-keys + Given a WP install + And a wp-content/mu-plugins/recurse-keys-immutable-offset.php file: + """ + [ 'stdClass', 'Recurse_Keys_Immutable_Offset_Test' ] ]; + } + ); + } + """ + And a setup-recurse-keys-immutable-offset.php file: + """ + 'value-a', 'keep' => 'value-keep', 'oldtok_b' => 'value-b' ) ); + update_option( 'recurse_keys_immutable_offset_test', array( 'item' => $object, 'other' => 'oldtok-other' ), false ); + echo $GLOBALS['wpdb']->get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_immutable_offset_test'" ); + """ + And a check-recurse-keys-immutable-offset.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_immutable_offset_test'" ); + """ + And I run `wp eval-file setup-recurse-keys-immutable-offset.php` + And save STDOUT as {ORIGINAL} + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then the return code should be 0 + And STDERR should contain: + """ + the whole value was left unchanged + """ + + When I run `wp eval-file check-recurse-keys-immutable-offset.php` + Then STDOUT should be: + """ + {ORIGINAL} + """ + And STDOUT should contain: + """ + s:8:"oldtok_b";s:7:"value-b"; + """ + + @require-mysql + Scenario: Leave the stored value unchanged when removing an offset throws after removing it with --recurse-keys + Given a WP install + And a wp-content/mu-plugins/recurse-keys-unset-then-throw.php file: + """ + [ 'stdClass', 'Recurse_Keys_Unset_Then_Throw_Test' ] ]; + } + ); + } + """ + And a setup-recurse-keys-unset-then-throw.php file: + """ + 'value-a', 'keep' => 'value-keep', 'oldtok_b' => 'value-b' ) ); + update_option( 'recurse_keys_unset_then_throw_test', array( 'item' => $object, 'other' => 'oldtok-other' ), false ); + echo $GLOBALS['wpdb']->get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_unset_then_throw_test'" ); + """ + And a check-recurse-keys-unset-then-throw.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_unset_then_throw_test'" ); + """ + And I run `wp eval-file setup-recurse-keys-unset-then-throw.php` + And save STDOUT as {ORIGINAL} + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then the return code should be 0 + And STDERR should contain: + """ + the whole value was left unchanged + """ + + When I run `wp eval-file check-recurse-keys-unset-then-throw.php` + Then STDOUT should be: + """ + {ORIGINAL} + """ + And STDOUT should contain: + """ + s:8:"oldtok_b";s:7:"value-b"; + """ + + @require-mysql @require-php-8.1 + Scenario: Leave nested objects unchanged when a readonly property of their parent cannot be updated with --recurse-keys + Given a WP install + And a wp-content/mu-plugins/recurse-keys-readonly-parent.php file: + """ + label = $label; + $this->child = $child; + } + } + if ( class_exists( 'WP_CLI' ) ) { + WP_CLI::add_hook( + 'search_replace_unserialize_options', + function () { + return [ 'allowed_classes' => [ 'stdClass', 'Recurse_Keys_Readonly_Parent_Test' ] ]; + } + ); + } + """ + And a setup-recurse-keys-readonly-parent.php file: + """ + oldtok_child = 'value-child'; + update_option( 'recurse_keys_readonly_parent_test', array( 'item' => new Recurse_Keys_Readonly_Parent_Test( 'oldtok-label', $child ) ), false ); + echo $GLOBALS['wpdb']->get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_readonly_parent_test'" ); + """ + And a check-recurse-keys-readonly-parent.php file: + """ + get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_readonly_parent_test'" ); + """ + And I run `wp eval-file setup-recurse-keys-readonly-parent.php` + And save STDOUT as {ORIGINAL} + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys` + Then the return code should be 0 + And STDERR should contain: + """ + Cannot modify readonly property + """ + + When I run `wp eval-file check-recurse-keys-readonly-parent.php` + Then STDOUT should be: + """ + {ORIGINAL} + """ + And STDOUT should contain: + """ + s:12:"oldtok_child";s:11:"value-child"; + """ + + @require-mysql + Scenario: Do not log a value that is left unchanged after a failed key replacement with --recurse-keys --log + Given a WP install + And a wp-content/mu-plugins/recurse-keys-failing-log.php file: + """ + [ 'stdClass', 'Recurse_Keys_Failing_Log_Test' ] ]; + } + ); + } + """ + And a setup-recurse-keys-failing-log.php file: + """ + 'oldtok-discarded-value' ) ); + update_option( 'recurse_keys_failing_log_a', array( 'item' => $object, 'other' => 'oldtok-discarded-sibling' ), false ); + update_option( 'recurse_keys_failing_log_b', array( 'other' => 'oldtok/next-row' ), false ); + """ + And I run `wp eval-file setup-recurse-keys-failing-log.php` + + When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys --log` + Then the return code should be 0 + And STDOUT should contain: + """ + < oldtok/next-row + """ + And STDOUT should not contain: + """ + oldtok-discarded + """ + And STDOUT should contain: + """ + Success: Made 1 replacement. + """ diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index c16b5adb..b3e4d305 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -67,6 +67,14 @@ class SearchReplacer { */ private $log_data = []; + /** + * Whether renaming the keys or property names of an object failed + * during the current run(). + * + * @var bool + */ + private $key_failure = false; + /** * @var int */ @@ -125,13 +133,32 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals * unserialising any subordinate arrays and performing the replace on those too. * Ignores any serialized objects unless $recurse_objects is set to true. * + * With key recursion enabled, the replacement is all or nothing: if + * renaming the keys or property names of any object in $data fails, the + * original $data is returned unchanged, and no log entries are kept for it. + * * @param array|string $data The data to operate on. * @param bool $serialised Does the value of $data need to be unserialized? * * @return array The original array with all elements replaced as needed. */ public function run( $data, $serialised = false ) { - return $this->run_recursively( $data, $serialised ); + if ( ! $this->recurse_keys ) { + return $this->run_recursively( $data, $serialised ); + } + + $log_position = count( $this->log_data ); + $this->key_failure = false; + try { + return $this->run_recursively( $data, $serialised ); + } catch ( Exception $exception ) { + if ( ! $this->key_failure ) { + throw $exception; + } + $this->key_failure = false; + array_splice( $this->log_data, $log_position ); + return $data; + } } /** @@ -241,8 +268,12 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis if ( $serialised ) { return serialize( $data ); } - } catch ( Exception $exception ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Intentionally empty. - + } catch ( Exception $exception ) { + // A failed key or property name replacement discards the whole + // value, so pass it on up to run(). + if ( $this->key_failure ) { + throw $exception; + } } return $data; @@ -400,9 +431,9 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) { * * Readonly properties (PHP 8.1+) are never renamed, and no property is * renamed onto a readonly property. Properties that share a PHP reference - * keep sharing it after a rename. If modifying the object fails part way, - * it is restored to its original property names and values before the - * error is passed on. + * keep sharing it after a rename. If modifying the object fails, the + * object is not restored: the whole value that run() is processing is + * left unchanged instead (see fail_key_replacement()). * * ArrayAccess implementations may normalize offsets on write. Offsets are * only renamed for implementations whose offset semantics are known @@ -479,69 +510,56 @@ private function replace_object_property_names( $data, $is_array_access, $recurs $renames = array_combine( array_keys( $renames ), array_keys( $renames ) ); } - // Take a reference to each property that is renamed, so that it keeps - // any reference it shares with other properties. Properties that keep - // their name are read and assigned normally, so that, for example, - // PHP 8.4 `set` hooks still apply to them. - $refs = array(); - $originals = array(); - foreach ( $renames as $key => $new_key ) { - if ( ! $is_array_access && $new_key !== $key ) { - $refs[ $key ] = &$data->$key; - $originals[ $key ] = $refs[ $key ]; - } else { - $originals[ $key ] = $this->read_property( $data, $is_array_access, $key ); + try { + // Take a reference to each property that is renamed, so that it keeps + // any reference it shares with other properties. Properties that keep + // their name are read and assigned normally, so that, for example, + // PHP 8.4 `set` hooks still apply to them. + $refs = array(); + $originals = array(); + foreach ( $renames as $key => $new_key ) { + if ( ! $is_array_access && $new_key !== $key ) { + $refs[ $key ] = &$data->$key; + $originals[ $key ] = $refs[ $key ]; + } else { + $originals[ $key ] = $this->read_property( $data, $is_array_access, $key ); + } } - } - // Stage all processed values before touching the object. - $log_position = count( $this->log_data ); - $values = array(); - foreach ( $renames as $key => $new_key ) { - $values[ $key ] = $this->run_recursively( $originals[ $key ], false, $recursion_level + 1, $visited_data ); - } + // Stage all processed values before touching the object. + $log_position = count( $this->log_data ); + $values = array(); + foreach ( $renames as $key => $new_key ) { + $values[ $key ] = $this->run_recursively( $originals[ $key ], false, $recursion_level + 1, $visited_data ); + if ( isset( $readonly[ $key ] ) && $values[ $key ] !== $originals[ $key ] ) { + throw new \Error( sprintf( 'Cannot modify readonly property %s::$%s', get_class( $data ), $key ) ); // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound + } + } - $removed = array(); - $written = array(); - $assigned = array(); - try { foreach ( $renames as $key => $new_key ) { if ( $new_key !== $key ) { $this->remove_property( $data, $is_array_access, $key ); - $removed[ $key ] = true; } } foreach ( $renames as $key => $new_key ) { if ( isset( $readonly[ $key ] ) ) { - if ( $values[ $key ] !== $originals[ $key ] ) { - throw new \Error( sprintf( 'Cannot modify readonly property %s::$%s', get_class( $data ), $key ) ); // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound - } continue; } if ( $is_array_access ) { $this->write_property( $data, true, $new_key, $values[ $key ] ); - if ( $new_key !== $key ) { - $written[] = $new_key; - } - continue; - } - if ( $new_key !== $key ) { + } elseif ( $new_key !== $key ) { $data->$new_key = &$refs[ $key ]; - $written[] = $new_key; $refs[ $key ] = $values[ $key ]; } else { - $data->$key = $values[ $key ]; - $assigned[ $key ] = true; + $data->$key = $values[ $key ]; } } } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound - $this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written, $assigned ); - throw $exception; + $this->fail_key_replacement( $data, $exception ); } catch ( Exception $exception ) { // ArrayAccess implementations may throw any exception, for example - // from offsetUnset() after an earlier offset was already removed. - $this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written, $assigned ); - throw $exception; + // from offsetUnset(). + $this->fail_key_replacement( $data, $exception ); } $this->commit_key_logs( $renames, $key_logs, $log_position ); @@ -549,54 +567,31 @@ private function replace_object_property_names( $data, $is_array_access, $recurs } /** - * Restore an object to its original property names and values after a failed modification. + * Abandon the current run() after renaming the keys or property names of an object failed. * - * Removed properties and offsets are added back at the end, so the - * properties and offsets that followed the first removed one are moved - * to the end as well, to restore the original order. Declared properties - * keep their position anyway and are not moved. + * The object may be left partly modified, so the whole value that is + * being processed is discarded: run() returns it unchanged instead. * - * @param object $data The object to restore. - * @param bool $is_array_access Whether the object implements ArrayAccess. - * @param array $renames Map of original key to destination key. - * @param array $originals Original values, by original key. - * @param array $refs References to the original properties, by original key. - * @param array $removed Original keys that were removed. - * @param array $written Destination keys that were written. - * @param array $assigned Original keys that kept their name and were assigned. - * @return void + * @param object $data The object that failed to be modified. + * @param \Throwable|Exception $exception The error or exception thrown. + * @return never + * + * @throws Exception Always, to unwind to run(). */ - private function restore_object( $data, $is_array_access, $renames, $originals, &$refs, $removed, $written, $assigned ) { - foreach ( $written as $name ) { - $this->remove_property( $data, $is_array_access, $name ); - } - $class = get_class( $data ); - $move = false; - foreach ( $renames as $key => $new_key ) { - if ( isset( $removed[ $key ] ) ) { - $move = true; - } - if ( $is_array_access ) { - if ( $move && ! isset( $removed[ $key ] ) ) { - $this->remove_property( $data, true, $key ); - } - $this->write_property( $data, true, $key, $originals[ $key ] ); - } elseif ( isset( $removed[ $key ] ) ) { - $data->$key = &$refs[ $key ]; - $refs[ $key ] = $originals[ $key ]; - } elseif ( $move && ! property_exists( $class, (string) $key ) ) { - // Move a dynamic property to the end, keeping any reference it shares. - $ref = &$data->$key; - unset( $data->$key ); - $data->$key = &$ref; - if ( isset( $assigned[ $key ] ) ) { - $ref = $originals[ $key ]; - } - unset( $ref ); - } elseif ( isset( $assigned[ $key ] ) ) { - $data->$key = $originals[ $key ]; - } + private function fail_key_replacement( $data, $exception ) { + if ( $this->key_failure ) { + // Already reported by a nested object. + throw $exception; } + $this->key_failure = true; + \WP_CLI::warning( + sprintf( + 'Skipping an inconvertible serialized object of type "%s": the whole value was left unchanged, so replacements might not be complete. Reason: %s.', + get_class( $data ), + $exception->getMessage() + ) + ); + throw new Exception( $exception->getMessage(), (int) $exception->getCode(), $exception ); } /** From 08eeaaf0f4a24c3121719d6dc8a929c0e20adefe Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 26 Nov 2026 17:52:00 +0000 Subject: [PATCH 10/10] Document that live objects in array input can still be partly modified Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- src/WP_CLI/SearchReplacer.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/WP_CLI/SearchReplacer.php b/src/WP_CLI/SearchReplacer.php index b3e4d305..296116e9 100644 --- a/src/WP_CLI/SearchReplacer.php +++ b/src/WP_CLI/SearchReplacer.php @@ -135,7 +135,10 @@ public function __construct( $from, $to, $recurse_objects = false, $regex = fals * * With key recursion enabled, the replacement is all or nothing: if * renaming the keys or property names of any object in $data fails, the - * original $data is returned unchanged, and no log entries are kept for it. + * original $data is returned and no log entries are kept for it. For a + * serialized string (which is all the command passes) that means the value + * is left unchanged. For an array holding live objects, those objects may + * still have been partly modified in place. * * @param array|string $data The data to operate on. * @param bool $serialised Does the value of $data need to be unserialized?