Skip to content

Commit 7a81682

Browse files
swissspidyclaude
andcommitted
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx
1 parent 04a944e commit 7a81682

2 files changed

Lines changed: 288 additions & 14 deletions

File tree

‎features/search-replace.feature‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2003,3 +2003,127 @@ Feature: Do global search/replace
20032003
"""
20042004
{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!":"keep!"}
20052005
"""
2006+
2007+
@require-mysql
2008+
Scenario: Do not log rejected key renames with --recurse-keys --log
2009+
Given a WP install
2010+
And a setup-recurse-keys-log.php file:
2011+
"""
2012+
<?php
2013+
update_option( 'recurse_keys_log_test', array( 'oldtok/key' => 'v1', 'newtok/key' => 'v2', 'other' => 'oldtok/value' ), false );
2014+
"""
2015+
And I run `wp eval-file setup-recurse-keys-log.php`
2016+
2017+
When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys --log`
2018+
Then STDERR should contain:
2019+
"""
2020+
two keys would map onto the same key
2021+
"""
2022+
And STDOUT should contain:
2023+
"""
2024+
< oldtok/value
2025+
"""
2026+
And STDOUT should contain:
2027+
"""
2028+
> newtok/value
2029+
"""
2030+
And STDOUT should not contain:
2031+
"""
2032+
oldtok/key
2033+
"""
2034+
2035+
@require-mysql @require-php-8.1
2036+
Scenario: Keep readonly property names and all values when renaming property names with --recurse-keys
2037+
Given a WP install
2038+
And a wp-content/mu-plugins/recurse-keys-readonly.php file:
2039+
"""
2040+
<?php
2041+
#[AllowDynamicProperties]
2042+
class Recurse_Keys_Readonly_Test {
2043+
public $oldtok_mutable;
2044+
public readonly string $oldtok_ro;
2045+
public function __construct( $mutable, $ro ) {
2046+
$this->oldtok_mutable = $mutable;
2047+
$this->oldtok_ro = $ro;
2048+
}
2049+
}
2050+
if ( class_exists( 'WP_CLI' ) ) {
2051+
WP_CLI::add_hook(
2052+
'search_replace_unserialize_options',
2053+
function () {
2054+
return [ 'allowed_classes' => [ 'stdClass', 'Recurse_Keys_Readonly_Test' ] ];
2055+
}
2056+
);
2057+
}
2058+
"""
2059+
And a setup-recurse-keys-readonly.php file:
2060+
"""
2061+
<?php
2062+
update_option( 'recurse_keys_readonly_test', array( 'item' => new Recurse_Keys_Readonly_Test( 'keep-mutable', 'keep-ro' ) ), false );
2063+
"""
2064+
And a check-recurse-keys-readonly.php file:
2065+
"""
2066+
<?php
2067+
echo $GLOBALS['wpdb']->get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_readonly_test'" );
2068+
"""
2069+
And I run `wp eval-file setup-recurse-keys-readonly.php`
2070+
2071+
When I try `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys`
2072+
Then the return code should be 0
2073+
2074+
When I run `wp eval-file check-recurse-keys-readonly.php`
2075+
Then STDOUT should contain:
2076+
"""
2077+
s:9:"oldtok_ro";s:7:"keep-ro";
2078+
"""
2079+
And STDOUT should contain:
2080+
"""
2081+
s:12:"keep-mutable";
2082+
"""
2083+
2084+
@require-mysql
2085+
Scenario: Preserve shared object property references when renaming property names with --recurse-keys
2086+
Given a WP install
2087+
And a setup-recurse-keys-object-refs.php file:
2088+
"""
2089+
<?php
2090+
$object = new stdClass();
2091+
$object->{'oldtok/a'} = 'shared';
2092+
$object->b = &$object->{'oldtok/a'};
2093+
update_option( 'recurse_keys_object_ref_test', array( 'item' => $object ), false );
2094+
"""
2095+
And a check-recurse-keys-object-refs.php file:
2096+
"""
2097+
<?php
2098+
$raw = $GLOBALS['wpdb']->get_var( "SELECT option_value FROM {$GLOBALS['wpdb']->options} WHERE option_name = 'recurse_keys_object_ref_test'" );
2099+
echo $raw, "\n";
2100+
echo preg_match( '/[Rr]:\d+;/', $raw ) ? 'HASREF' : 'NOREF', "\n";
2101+
$value = get_option( 'recurse_keys_object_ref_test' );
2102+
$value['item']->b = 'changed';
2103+
echo $value['item']->{'newtok/a'};
2104+
"""
2105+
And I run `wp eval-file setup-recurse-keys-object-refs.php`
2106+
2107+
When I run `wp search-replace 'oldtok' 'newtok' wp_options --include-columns=option_value --recurse-keys`
2108+
Then STDOUT should contain:
2109+
"""
2110+
Success:
2111+
"""
2112+
2113+
When I run `wp eval-file check-recurse-keys-object-refs.php`
2114+
Then STDOUT should contain:
2115+
"""
2116+
s:8:"newtok/a";
2117+
"""
2118+
And STDOUT should contain:
2119+
"""
2120+
"shared"
2121+
"""
2122+
And STDOUT should contain:
2123+
"""
2124+
HASREF
2125+
"""
2126+
And STDOUT should contain:
2127+
"""
2128+
changed
2129+
"""

‎src/WP_CLI/SearchReplacer.php‎

Lines changed: 164 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,48 @@ private function replace_key( $key ) {
308308
return is_string( $new_key ) ? $new_key : $key;
309309
}
310310

311+
/**
312+
* Work out the replacement for each key of a container.
313+
*
314+
* Log entries produced while replacing the keys are kept apart from the
315+
* value log, so that they can be committed only once the container
316+
* accepts the renames (see commit_key_logs()).
317+
*
318+
* @param array<int|string> $keys The keys or property names.
319+
* @return array{0: array<int|string, int|string>, 1: array<int|string, string[]>} Map of original key to
320+
* destination key, and the pending log entries for each key.
321+
*/
322+
private function plan_key_renames( $keys ) {
323+
$renames = array();
324+
$key_logs = array();
325+
foreach ( $keys as $key ) {
326+
$mark = count( $this->log_data );
327+
$renames[ $key ] = $this->replace_key( $key );
328+
$key_logs[ $key ] = array_splice( $this->log_data, $mark );
329+
}
330+
return array( $renames, $key_logs );
331+
}
332+
333+
/**
334+
* Add the log entries of the keys that were actually renamed.
335+
*
336+
* @param array<int|string, int|string> $renames Map of original key to destination key.
337+
* @param array<int|string, string[]> $key_logs Pending log entries for each key.
338+
* @param int $position Position in the log at which to insert the entries.
339+
* @return void
340+
*/
341+
private function commit_key_logs( $renames, $key_logs, $position ) {
342+
$accepted = array();
343+
foreach ( $renames as $key => $new_key ) {
344+
if ( $new_key !== $key ) {
345+
$accepted = array_merge( $accepted, $key_logs[ $key ] );
346+
}
347+
}
348+
if ( $accepted ) {
349+
array_splice( $this->log_data, $position, 0, $accepted );
350+
}
351+
}
352+
311353
/**
312354
* Recurse into an array, replacing string keys as well as values.
313355
*
@@ -322,20 +364,19 @@ private function replace_key( $key ) {
322364
* @return array The processed array.
323365
*/
324366
private function replace_array_keys( $data, $recursion_level, $visited_data ) {
325-
$renames = array();
326-
foreach ( array_keys( $data ) as $key ) {
327-
$renames[ $key ] = $this->replace_key( $key );
328-
}
367+
list( $renames, $key_logs ) = $this->plan_key_renames( array_keys( $data ) );
329368
if ( $this->has_destination_collision( $renames, false ) ) {
330369
\WP_CLI::warning( 'Skipping key replacement for an array: two keys would map onto the same key and a value would be lost.' );
331370
$renames = array_combine( array_keys( $renames ), array_keys( $renames ) );
332371
}
333-
$replaced = array();
372+
$log_position = count( $this->log_data );
373+
$replaced = array();
334374
foreach ( $data as $key => &$value ) {
335375
$value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data );
336376
$replaced[ $renames[ $key ] ] =& $value;
337377
}
338378
unset( $value );
379+
$this->commit_key_logs( $renames, $key_logs, $log_position );
339380
return $replaced;
340381
}
341382

@@ -348,6 +389,12 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) {
348389
* the property names are left unchanged (values are still replaced) and a
349390
* warning is emitted instead of silently discarding a value.
350391
*
392+
* Readonly properties (PHP 8.1+) are never renamed, and no property is
393+
* renamed onto a readonly property. Properties that share a PHP reference
394+
* keep sharing it after a rename. If modifying the object fails part way,
395+
* it is restored to its original property names and values before the
396+
* error is passed on.
397+
*
351398
* ArrayAccess implementations may normalize offsets on write. Offsets are
352399
* only renamed for implementations whose offset semantics are known
353400
* (ArrayObject, ArrayIterator and the Requests case-insensitive
@@ -361,10 +408,11 @@ private function replace_array_keys( $data, $recursion_level, $visited_data ) {
361408
* @return object The processed object.
362409
*/
363410
private function replace_object_property_names( $data, $is_array_access, $recursion_level, $visited_data ) {
364-
$renames = array();
411+
$keys = array();
365412
foreach ( $data as $key => $value ) {
366-
$renames[ $key ] = $this->replace_key( $key );
413+
$keys[] = $key;
367414
}
415+
list( $renames, $key_logs ) = $this->plan_key_renames( $keys );
368416

369417
$case_insensitive = false;
370418
$keep_offsets = false;
@@ -376,6 +424,20 @@ private function replace_object_property_names( $data, $is_array_access, $recurs
376424
}
377425
}
378426

427+
$readonly = $is_array_access ? array() : $this->get_readonly_property_names( $data );
428+
foreach ( $renames as $key => $new_key ) {
429+
if ( $new_key !== $key && ( isset( $readonly[ $key ] ) || isset( $readonly[ $new_key ] ) ) ) {
430+
\WP_CLI::warning(
431+
sprintf(
432+
'Skipping key replacement for property "%s" of an object of class "%s": a readonly property cannot be renamed or overwritten.',
433+
$key,
434+
get_class( $data )
435+
)
436+
);
437+
$renames[ $key ] = $key;
438+
}
439+
}
440+
379441
$renamed = false;
380442
foreach ( $renames as $key => $new_key ) {
381443
if ( $new_key !== $key ) {
@@ -397,20 +459,108 @@ private function replace_object_property_names( $data, $is_array_access, $recurs
397459
$renames = array_combine( array_keys( $renames ), array_keys( $renames ) );
398460
}
399461

400-
// Stage all processed values before touching the object.
401-
$values = array();
462+
// Take a reference to each writable property, so that renaming a
463+
// property keeps any reference it shares with other properties.
464+
$refs = array();
465+
$originals = array();
402466
foreach ( $renames as $key => $new_key ) {
403-
$values[ $key ] = $this->run_recursively( $this->read_property( $data, $is_array_access, $key ), false, $recursion_level + 1, $visited_data );
467+
if ( $is_array_access || isset( $readonly[ $key ] ) ) {
468+
$originals[ $key ] = $this->read_property( $data, $is_array_access, $key );
469+
} else {
470+
$refs[ $key ] = &$data->$key;
471+
$originals[ $key ] = $refs[ $key ];
472+
}
404473
}
474+
475+
// Stage all processed values before touching the object.
476+
$log_position = count( $this->log_data );
477+
$values = array();
405478
foreach ( $renames as $key => $new_key ) {
406-
if ( $new_key !== $key ) {
407-
$this->remove_property( $data, $is_array_access, $key );
479+
$values[ $key ] = $this->run_recursively( $originals[ $key ], false, $recursion_level + 1, $visited_data );
480+
}
481+
482+
$removed = array();
483+
$written = array();
484+
try {
485+
foreach ( $renames as $key => $new_key ) {
486+
if ( $new_key !== $key ) {
487+
$this->remove_property( $data, $is_array_access, $key );
488+
$removed[ $key ] = true;
489+
}
490+
}
491+
foreach ( $renames as $key => $new_key ) {
492+
if ( isset( $readonly[ $key ] ) ) {
493+
if ( $values[ $key ] !== $originals[ $key ] ) {
494+
throw new \Error( sprintf( 'Cannot modify readonly property %s::$%s', get_class( $data ), $key ) ); // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound
495+
}
496+
continue;
497+
}
498+
if ( $is_array_access ) {
499+
$this->write_property( $data, true, $new_key, $values[ $key ] );
500+
if ( $new_key !== $key ) {
501+
$written[] = $new_key;
502+
}
503+
continue;
504+
}
505+
if ( $new_key !== $key ) {
506+
$data->$new_key = &$refs[ $key ];
507+
$written[] = $new_key;
508+
}
509+
$refs[ $key ] = $values[ $key ];
408510
}
511+
} catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound
512+
$this->restore_object( $data, $is_array_access, $renames, $originals, $refs, $removed, $written );
513+
throw $exception;
514+
}
515+
516+
$this->commit_key_logs( $renames, $key_logs, $log_position );
517+
return $data;
518+
}
519+
520+
/**
521+
* Restore an object to its original property names and values after a failed modification.
522+
*
523+
* @param object $data The object to restore.
524+
* @param bool $is_array_access Whether the object implements ArrayAccess.
525+
* @param array<int|string, int|string> $renames Map of original key to destination key.
526+
* @param array<int|string, mixed> $originals Original values, by original key.
527+
* @param array<int|string, mixed> $refs References to the original properties, by original key.
528+
* @param array<int|string, bool> $removed Original keys that were removed.
529+
* @param array<int|string> $written Destination keys that were written.
530+
* @return void
531+
*/
532+
private function restore_object( $data, $is_array_access, $renames, $originals, &$refs, $removed, $written ) {
533+
foreach ( $written as $name ) {
534+
$this->remove_property( $data, $is_array_access, $name );
409535
}
410536
foreach ( $renames as $key => $new_key ) {
411-
$this->write_property( $data, $is_array_access, $new_key, $values[ $key ] );
537+
if ( $is_array_access ) {
538+
$this->write_property( $data, true, $key, $originals[ $key ] );
539+
} elseif ( array_key_exists( $key, $refs ) ) {
540+
if ( isset( $removed[ $key ] ) ) {
541+
$data->$key = &$refs[ $key ];
542+
}
543+
$refs[ $key ] = $originals[ $key ];
544+
}
412545
}
413-
return $data;
546+
}
547+
548+
/**
549+
* Get the names of the readonly properties of an object.
550+
*
551+
* Readonly properties exist as of PHP 8.1; on older versions there are none.
552+
*
553+
* @param object $data The object to inspect.
554+
* @return array<string, bool> Readonly property names as keys.
555+
*/
556+
private function get_readonly_property_names( $data ) {
557+
$names = array();
558+
foreach ( ( new \ReflectionObject( $data ) )->getProperties() as $property ) {
559+
if ( method_exists( $property, 'isReadOnly' ) && $property->isReadOnly() ) {
560+
$names[ $property->getName() ] = true;
561+
}
562+
}
563+
return $names;
414564
}
415565

416566
/**

0 commit comments

Comments
 (0)