Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 42 additions & 5 deletions lib/experimental/experiments/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,18 +173,55 @@ function gutenberg_initialize_experiments_settings() {
'gutenberg-experiments',
'gutenberg-experiments',
array(
'label' => __( 'Gutenberg Experiments', 'gutenberg' ),
'show_in_rest' => array(
'label' => __( 'Gutenberg Experiments', 'gutenberg' ),
'show_in_rest' => array(
'schema' => array(
'type' => 'object',
'properties' => $properties,
'type' => 'object',
'properties' => $properties,
/*
* The stored option routinely holds experiments that are no
* longer registered, because switching between branches
* leaves the keys of the other branch behind.
*
* `WP_REST_Settings_Controller` defaults `additionalProperties`
* to false and replaces any value that fails its schema with
* null, so without this a single stale key would blank out the
* whole option in the REST response and make every toggle on
* the Experiments screen read as "off".
*/
'additionalProperties' => true,
),
),
'default' => array(),
'sanitize_callback' => 'gutenberg_sanitize_experiments_option',
'default' => array(),
)
);
}

/**
* Normalizes the `gutenberg-experiments` option to a map of experiment id to boolean.
*
* Unregistered experiments are kept rather than dropped: they usually belong to
* a branch the user can switch back to, and discarding them here would silently
* lose settings they never asked to change.
*
* @param mixed $value The value being saved.
* @return array<string, bool> The sanitized value.
*/
function gutenberg_sanitize_experiments_option( $value ) {
if ( ! is_array( $value ) ) {
return array();
}

$sanitized = array();

foreach ( $value as $experiment_id => $enabled ) {
$sanitized[ (string) $experiment_id ] = rest_sanitize_boolean( $enabled );
}

return $sanitized;
}

add_action( 'rest_api_init', 'gutenberg_initialize_experiments_settings' );

/**
Expand Down
172 changes: 172 additions & 0 deletions phpunit/experimental/experiments-settings-test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
<?php
/**
* Tests for the `gutenberg-experiments` setting as exposed through the REST API.
*
* @package gutenberg
*
* @covers ::gutenberg_initialize_experiments_settings
*/
class Gutenberg_Experiments_Settings_Test extends WP_UnitTestCase {

/**
* @var int
*/
protected static $admin_id;

public static function wpSetUpBeforeClass( $factory ) {
self::$admin_id = $factory->user->create( array( 'role' => 'administrator' ) );
}

public static function wpTearDownAfterClass() {
self::delete_user( self::$admin_id );
}

public function set_up() {
parent::set_up();

wp_set_current_user( self::$admin_id );

// The bootstrap seeds this option through `$wp_tests_options`, which
// short-circuits `get_option()` and cannot be overwritten per test.
remove_all_filters( 'pre_option_gutenberg-experiments' );

global $wp_rest_server;
$wp_rest_server = new Spy_REST_Server();
do_action( 'rest_api_init', $wp_rest_server );
}

public function tear_down() {
delete_option( 'gutenberg-experiments' );

global $wp_rest_server;
$wp_rest_server = null;

parent::tear_down();
}

/**
* Reads the `gutenberg-experiments` value out of `GET /wp/v2/settings`.
*
* @return mixed
*/
private function get_experiments_setting() {
$response = rest_get_server()->dispatch( new WP_REST_Request( 'GET', '/wp/v2/settings' ) );

$this->assertSame( 200, $response->get_status() );

$data = $response->get_data();

$this->assertArrayHasKey( 'gutenberg-experiments', $data );

return $data['gutenberg-experiments'];
}

public function test_returns_registered_experiments() {
update_option(
'gutenberg-experiments',
array( 'gutenberg-block-experiments' => true )
);

$this->assertSame(
array( 'gutenberg-block-experiments' => true ),
$this->get_experiments_setting()
);
}

/**
* Stale keys are routine: switching between branches that register
* different experiments leaves behind experiments that no longer exist.
* They must not invalidate the whole option, which would make every
* toggle on the Experiments screen read as "off".
*/
public function test_unregistered_experiments_do_not_invalidate_the_setting() {
update_option(
'gutenberg-experiments',
array(
'gutenberg-block-experiments' => true,
'some-removed-experiment' => true,
)
);

$value = $this->get_experiments_setting();

$this->assertIsArray( $value, 'The setting should not be null when an unknown experiment is stored.' );
$this->assertTrue( $value['gutenberg-block-experiments'] );
}

/**
* A stale key belongs to a branch the user may switch back to, so reading
* the setting must not drop it.
*/
public function test_unregistered_experiments_are_preserved() {
update_option(
'gutenberg-experiments',
array(
'gutenberg-block-experiments' => true,
'some-removed-experiment' => true,
)
);

$value = $this->get_experiments_setting();

$this->assertArrayHasKey( 'some-removed-experiment', $value );
$this->assertTrue( $value['some-removed-experiment'] );
}

/**
* Saving one experiment must not drop the ones already stored, including
* those that are no longer registered.
*/
public function test_saving_an_experiment_keeps_unregistered_ones() {
update_option(
'gutenberg-experiments',
array( 'some-removed-experiment' => true )
);

$request = new WP_REST_Request( 'POST', '/wp/v2/settings' );
$request->set_body_params(
array(
'gutenberg-experiments' => array(
'some-removed-experiment' => true,
'gutenberg-block-experiments' => true,
),
)
);

$response = rest_get_server()->dispatch( $request );

$this->assertSame( 200, $response->get_status() );
$this->assertSame(
array(
'some-removed-experiment' => true,
'gutenberg-block-experiments' => true,
),
get_option( 'gutenberg-experiments' )
);
}

/**
* @covers ::gutenberg_sanitize_experiments_option
*/
public function test_sanitize_casts_legacy_checkbox_values_to_booleans() {
// The pre-React screen submitted a checkbox form, which stores '1'.
update_option(
'gutenberg-experiments',
array( 'gutenberg-block-experiments' => '1' )
);

$this->assertSame(
array( 'gutenberg-block-experiments' => true ),
get_option( 'gutenberg-experiments' )
);
}

/**
* @covers ::gutenberg_sanitize_experiments_option
*/
public function test_sanitize_rejects_a_value_that_is_not_a_map() {
update_option( 'gutenberg-experiments', 'not-an-array' );

$this->assertSame( array(), get_option( 'gutenberg-experiments' ) );
}
}
51 changes: 37 additions & 14 deletions routes/experiments-home/stage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Page } from '@wordpress/admin-ui';
import { Spinner } from '@wordpress/components';
import { Notice, Spinner } from '@wordpress/components';
import { useEntityRecord } from '@wordpress/core-data';
import { useDispatch } from '@wordpress/data';
import { DataForm } from '@wordpress/dataviews';
Expand Down Expand Up @@ -36,9 +36,24 @@ function ExperimentsPage() {
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );

const storedExperiments = siteSettings?.[ 'gutenberg-experiments' ];

// `GET /wp/v2/settings` returns `null` for a setting whose stored value
// fails its schema. That is not the same as "no experiments are enabled":
// the real state is unknown. Rendering the toggles anyway would show every
// experiment as off, and saving one would replace whatever is really
// stored, so the form is withheld instead.
const areExperimentsUnreadable =
siteSettings !== undefined &&
storedExperiments !== undefined &&
( typeof storedExperiments !== 'object' || storedExperiments === null );

const gutenbergExperiments = useMemo(
() => siteSettings?.[ 'gutenberg-experiments' ] || {},
[ siteSettings ]
() =>
typeof storedExperiments === 'object' && storedExperiments !== null
? ( storedExperiments as Record< string, unknown > )
: {},
[ storedExperiments ]
);

const settings = useMemo( () => {
Expand Down Expand Up @@ -191,17 +206,25 @@ function ExperimentsPage() {
</Stack>
</Card.Content>
</Card.Root>
<DataForm
data={ settings }
fields={ fields }
form={ {
layout: { type: 'card' },
fields: formFields,
} }
onChange={ ( values ) => {
setSettings( values );
} }
/>
{ areExperimentsUnreadable ? (
<Notice status="error" isDismissible={ false }>
{ __(
'Your saved experiments could not be read, so this screen cannot show which ones are on. The toggles are hidden because changing one would replace the saved settings. To restore the screen, reset the "gutenberg-experiments" option to an empty value.'
) }
</Notice>
) : (
<DataForm
data={ settings }
fields={ fields }
form={ {
layout: { type: 'card' },
fields: formFields,
} }
onChange={ ( values ) => {
setSettings( values );
} }
/>
) }
</Stack>
</Page>
);
Expand Down
Loading