Skip to content

Commit d3b793f

Browse files
committed
Users: Ensure switching to current user doesn't reinstantiate current user.
Prevent `wp_set_current_user()` from reinstantiating the current user when the user ID is passed as a string, eg `wp_set_current_user( (string) get_current_user_id() )`. This restores the function's previous behaviour of returning early in the event the IDs loosely match. Follow up to r57882. Props westonruter, peterwilsoncc. Fixes #64628. git-svn-id: https://develop.svn.wordpress.org/trunk@61633 602fd350-edb4-49c9-b593-d223f7449a82
1 parent d082b28 commit d3b793f

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

src/wp-includes/pluggable.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ function wp_set_current_user( $id, $name = '' ) {
3030
// If `$id` matches the current user, there is nothing to do.
3131
if ( isset( $current_user )
3232
&& ( $current_user instanceof WP_User )
33-
&& ( $id === $current_user->ID )
33+
&& ( (int) $id === $current_user->ID )
3434
&& ( null !== $id )
3535
) {
3636
return $current_user;

tests/phpunit/tests/user/wpSetCurrentUser.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,34 @@ public function test_should_set_by_name_if_id_is_null() {
5757
$this->assertSame( $user, wp_get_current_user() );
5858
$this->assertSame( self::$user_id2, get_current_user_id() );
5959
}
60+
61+
/**
62+
* Ensure user switching doesn't occur for the same user, even if type is non-int.
63+
*
64+
* @ticket 64628
65+
*
66+
* @dataProvider data_should_not_switch_to_same_user_type_equivalency
67+
*/
68+
public function test_should_not_switch_to_same_user_type_equivalency( string $type_function ) {
69+
wp_set_current_user( self::$user_id );
70+
$this->assertSame( self::$user_id, get_current_user_id(), "Current user's ID should match the ID of the user switched to." );
71+
72+
$action = new MockAction();
73+
add_action( 'set_current_user', array( $action, 'action' ) );
74+
75+
wp_set_current_user( $type_function( self::$user_id ) );
76+
$this->assertSame( 0, $action->get_call_count(), 'set_current_user should not be fired when switching to the same user.' );
77+
}
78+
79+
/**
80+
* Data provider for test_should_not_switch_to_same_user_type_equivalency.
81+
*
82+
* @return array[] Data provider.
83+
*/
84+
public function data_should_not_switch_to_same_user_type_equivalency(): array {
85+
return array(
86+
'integer' => array( 'type_function' => 'intval' ),
87+
'string' => array( 'type_function' => 'strval' ),
88+
);
89+
}
6090
}

0 commit comments

Comments
 (0)