diff --git a/features/search-replace.feature b/features/search-replace.feature index 05f176f7..5fa01dc1 100644 --- a/features/search-replace.feature +++ b/features/search-replace.feature @@ -1638,3 +1638,805 @@ Feature: Do global search/replace """ Plain other.example content """ + + @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: + """ + 'v1', 'https://new.example.com/key' => 'v2', 'other' => 'https://old.example.com/value' ), false ); + """ + And a check-recurse-keys-collision.php file: + """ + 'v1', 'https://new.example.com/prop' => 'v2', 'other' => 'https://old.example.com/value' ), 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 + """ + + 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: + """ + '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` + 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: + """ + 'v1', + 'newold' => 'v2', + ); + $result = unserialize( $replacer->run( serialize( (object) $data ) ) ); + 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" + """ + + @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: + """ + '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:14:"newtok_mutable";s:12:"keep-mutable"; + """ + And STDOUT should not contain: + """ + "oldtok_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 + """ + + @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: 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: + """ + [ '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"; + """ + + @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/Search_Replace_Command.php b/src/Search_Replace_Command.php index d6e73804..fc4d69ff 100644 --- a/src/Search_Replace_Command.php +++ b/src/Search_Replace_Command.php @@ -37,6 +37,11 @@ class Search_Replace_Command extends WP_CLI_Command { */ private $recurse_objects; + /** + * @var bool + */ + private $recurse_keys; + /** * @var bool */ @@ -220,6 +225,10 @@ class Search_Replace_Command extends WP_CLI_Command { * : Enable recursing into objects to replace strings. Defaults to true; * pass --no-recurse-objects to disable. * + * [--recurse-keys] + * : Enable recursing into array keys and object properties to replace strings. + * Defaults to false; pass --recurse-keys to enable. + * * [--verbose] * : Prints rows to the console as they're updated. * @@ -296,7 +305,7 @@ class Search_Replace_Command extends WP_CLI_Command { * fi * * @param array $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; @@ -342,6 +351,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 ); @@ -682,7 +692,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 ); @@ -787,7 +797,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..296116e9 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 */ @@ -62,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 */ @@ -81,11 +94,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; @@ -118,13 +133,35 @@ 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 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? * * @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; + } } /** @@ -180,9 +217,13 @@ 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 ); - foreach ( $keys as $key ) { - $data[ $key ] = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data ); + 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 ); + } } } elseif ( $this->recurse_objects && ( is_object( $data ) || $data instanceof \__PHP_Incomplete_Class ) ) { if ( $data instanceof \__PHP_Incomplete_Class ) { @@ -196,12 +237,16 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } else { try { $is_array_access = $data instanceof \ArrayAccess; - 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; + 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; + } } } } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound @@ -220,46 +265,426 @@ private function run_recursively( $data, $serialised, $recursion_level = 0, $vis } } } elseif ( is_string( $data ) ) { - if ( $this->logging ) { - $old_data = $data; + $data = $this->replace_string( $data ); + } + + if ( $serialised ) { + return serialize( $data ); + } + } 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; + } + + /** + * 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; + } + + /** + * Replace occurrences of the search string within an array key or property name. + * + * Integer keys are returned unchanged. If the replacement fails (for + * example a PCRE error in regex mode), the original key is kept instead of + * turning it into an empty string. + * + * @param int|string $key The key or property name. + * @return int|string The replaced key, or the original key. + */ + private function replace_key( $key ) { + if ( ! is_string( $key ) ) { + return $key; + } + $new_key = $this->replace_string( $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 ); + // 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 ); + } + + /** + * 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 ) { + foreach ( $key_logs[ $key ] as $entry ) { + $accepted[] = $entry; } - 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 ( $accepted ) { + array_splice( $this->log_data, $position, 0, $accepted ); + } + } + + /** + * 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 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. + * @param array $visited_data Previously seen arrays and objects. + * @return array The processed array. + */ + private function replace_array_keys( $data, $recursion_level, $visited_data ) { + 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 ) ); + } + $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; + } + + /** + * Recurse into an object, replacing string property names as well as values. + * + * 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. + * + * 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, 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 + * (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. + * @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 ) { + $keys = array(); + foreach ( $data as $key => $value ) { + $keys[] = $key; + } + 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; } - if ( $this->logging && $old_data !== $data ) { - $this->log_data[] = $old_data; + } + } + + $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; + } + } + + $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 ) { + $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 ) ); + } + + 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 ); } } - if ( $serialised ) { - return serialize( $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 + } } - } catch ( Exception $exception ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Intentionally empty. + foreach ( $renames as $key => $new_key ) { + if ( $new_key !== $key ) { + $this->remove_property( $data, $is_array_access, $key ); + } + } + foreach ( $renames as $key => $new_key ) { + if ( isset( $readonly[ $key ] ) ) { + continue; + } + if ( $is_array_access ) { + $this->write_property( $data, true, $new_key, $values[ $key ] ); + } elseif ( $new_key !== $key ) { + $data->$new_key = &$refs[ $key ]; + $refs[ $key ] = $values[ $key ]; + } else { + $data->$key = $values[ $key ]; + } + } + } catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound + $this->fail_key_replacement( $data, $exception ); + } catch ( Exception $exception ) { + // ArrayAccess implementations may throw any exception, for example + // from offsetUnset(). + $this->fail_key_replacement( $data, $exception ); } + $this->commit_key_logs( $renames, $key_logs, $log_position ); return $data; } + /** + * Abandon the current run() after renaming the keys or property names of an object failed. + * + * 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 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 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 ); + } + + /** + * 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; + } + + /** + * 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. + * + * @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.