Skip to content

Commit

Permalink
Raw Options: prevent update_raw_option from creating multiple values (#…
Browse files Browse the repository at this point in the history
…11992)

* Raw Options: prevent update_raw_option from creating multiple values

* Update class.jetpack-options.php

Co-Authored-By: gititon <gititon@users.noreply.github.com>
  • Loading branch information
2 people authored and kraftbj committed Apr 16, 2019
1 parent fe5b739 commit 50c4d1a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
15 changes: 12 additions & 3 deletions class.jetpack-options.php
Original file line number Diff line number Diff line change
Expand Up @@ -368,9 +368,17 @@ static function update_raw_option( $name, $value, $autoload = false ) {
global $wpdb;
$autoload_value = $autoload ? 'yes' : 'no';

$old_value = $wpdb->get_var(
$wpdb->prepare(
"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1",
$name
)
);
if ( $old_value === $value ) {
return false;
}

$serialized_value = maybe_serialize( $value );
// try updating, if no update then insert
// TODO: try to deal with the fact that unchanged values can return updated_num = 0
// below we used "insert ignore" to at least suppress the resulting error
$updated_num = $wpdb->query(
$wpdb->prepare(
Expand All @@ -380,6 +388,7 @@ static function update_raw_option( $name, $value, $autoload = false ) {
)
);

// Try inserting the option if the value doesn't exits.
if ( ! $updated_num ) {
$updated_num = $wpdb->query(
$wpdb->prepare(
Expand All @@ -389,7 +398,7 @@ static function update_raw_option( $name, $value, $autoload = false ) {
)
);
}
return $updated_num;
return (bool) $updated_num;
}

/**
Expand Down
10 changes: 10 additions & 0 deletions tests/php/test_class.jetpack-options.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,14 @@ function test_raw_option_delete_will_bypass_wp_cache_and_filters() {
remove_action( 'added_option', array( $this, 'cache_option' ), 10, 2 );
remove_filter( 'option_test_option', array( $this, 'get_test_option_from_cache' ) );
}

function test_raw_option_update_with_duplicate_value_returns_false() {
Jetpack_Options::delete_raw_option( 'test_option_2' );

Jetpack_Options::update_raw_option( 'test_option_2', 'blue' );
$this->assertEquals( 'blue', Jetpack_Options::get_raw_option( 'test_option_2' ) );

$this->assertFalse( Jetpack_Options::update_raw_option( 'test_option_2', 'blue' ) );
$this->assertTrue( Jetpack_Options::update_raw_option( 'test_option_2', 'yellow' ) );
}
}

0 comments on commit 50c4d1a

Please sign in to comment.