Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport new endpoint for Pattern Directory categories #3905

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -33,8 +33,21 @@ public function __construct() {
* Registers the necessary REST API routes.
*
* @since 5.8.0
* @since 6.2.0 Added pattern directory categories endpoint.
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/categories',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_pattern_categories' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
),
)
);

register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/patterns',
Expand All @@ -50,6 +63,105 @@ public function register_routes() {
);
}

/**
* Retrieve block patterns categories.
*
* @since 6.2.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function get_pattern_categories( $request ) {
$query_args = array( 'locale' => get_user_locale() );
$transient_key = 'wp_remote_block_pattern_categories_' . md5( serialize( $query_args ) );

/**
* Use network-wide transient to improve performance. The locale is the only site
* configuration that affects the response, and it's included in the transient key.
*/
$raw_pattern_categories = get_site_transient( $transient_key );

if ( ! $raw_pattern_categories ) {
$api_url = 'http://api.wordpress.org/patterns/1.0/?categories&' . build_query( $query_args );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}

/**
* Default to a short TTL, to mitigate cache stampedes on high-traffic sites.
* This assumes that most errors will be short-lived, e.g., packet loss that causes the
* first request to fail, but a follow-up one will succeed. The value should be high
* enough to avoid stampedes, but low enough to not interfere with users manually
* re-trying a failed request.
*/
$cache_ttl = 5;
$wporg_response = wp_remote_get( $api_url );
$raw_pattern_categories = json_decode( wp_remote_retrieve_body( $wporg_response ) );
if ( is_wp_error( $wporg_response ) ) {
$raw_pattern_categories = $wporg_response;

} elseif ( ! is_array( $raw_pattern_categories ) ) {
// HTTP request succeeded, but response data is invalid.
$raw_pattern_categories = new WP_Error(
'pattern_directory_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
),
array(
'response' => wp_remote_retrieve_body( $wporg_response ),
)
);

} else {
// Response has valid data.
$cache_ttl = HOUR_IN_SECONDS;
}

set_site_transient( $transient_key, $raw_pattern_categories, $cache_ttl );
}

if ( is_wp_error( $raw_pattern_categories ) ) {
$raw_pattern_categories->add_data( array( 'status' => 500 ) );

return $raw_pattern_categories;
}

$response = array();

if ( $raw_pattern_categories ) {
foreach ( $raw_pattern_categories as $category ) {
$response[] = $this->prepare_response_for_collection(
$this->prepare_pattern_category_for_response( $category, $request )
);
}
}

return new WP_REST_Response( $response );
}

/**
* Prepare a raw block pattern category before it gets output in a REST API response.
*
* @since 6.2.0
*
* @param object $item Raw pattern category from api.wordpress.org, before any changes.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response
*/
public function prepare_pattern_category_for_response( $item, $request ) {
$raw_pattern_category = array(
'id' => absint( $item->id ),
'name' => sanitize_text_field( $item->name ),
'slug' => sanitize_title_with_dashes( $item->slug ),
);

$prepared_pattern_category = $this->add_additional_fields_to_object( $raw_pattern_category, $request );

return new WP_REST_Response( $prepared_pattern_category );
}

/**
* Checks whether a given request has permission to view the local block pattern directory.
*
Expand Down Expand Up @@ -103,6 +215,7 @@ public function get_items( $request ) {
'search' => true,
'slug' => true,
);

$query_args = array_intersect_key( $request->get_params(), $valid_query_args );

$query_args['locale'] = get_user_locale();
Expand Down
33 changes: 33 additions & 0 deletions tests/phpunit/tests/rest-api/rest-pattern-directory-controller.php
Expand Up @@ -102,11 +102,13 @@ public function assertPatternMatchesSchema( $pattern ) {
* @covers WP_REST_Pattern_Directory_Controller::register_routes
*
* @since 5.8.0
* @since 6.2.0 Added pattern directory categories endpoint.
*/
public function test_register_routes() {
$routes = rest_get_server()->get_routes();

$this->assertArrayHasKey( '/wp/v2/pattern-directory/patterns', $routes );
$this->assertArrayHasKey( '/wp/v2/pattern-directory/categories', $routes );
}

/**
Expand Down Expand Up @@ -510,6 +512,37 @@ public function data_get_items_query_args() {
);
}

/**
* @covers WP_REST_Pattern_Directory_Controller::prepare_pattern_category_for_response
*
* @since 6.2.0
*
* @ticket 57551
*/
public function test_prepare_pattern_category_for_response() {
$raw_categories = array(
(object) array(
'id' => 3,
'name' => 'Columns',
'slug' => 'columns',
'description' => 'A description',
),
);

$prepared_category = static::$controller->prepare_response_for_collection(
static::$controller->prepare_pattern_category_for_response( $raw_categories[0], new WP_REST_Request() )
);

$this->assertSame(
array(
'id' => 3,
'name' => 'Columns',
'slug' => 'columns',
),
$prepared_category,
);
}

/**
* @doesNotPerformAssertions
*/
Expand Down
1 change: 1 addition & 0 deletions tests/phpunit/tests/rest-api/rest-schema-setup.php
Expand Up @@ -106,6 +106,7 @@ public function test_expected_routes_in_schema() {
'/wp/v2/pages/(?P<parent>[\\d]+)/revisions/(?P<id>[\\d]+)',
'/wp/v2/pages/(?P<id>[\\d]+)/autosaves',
'/wp/v2/pages/(?P<parent>[\\d]+)/autosaves/(?P<id>[\\d]+)',
'/wp/v2/pattern-directory/categories',
'/wp/v2/pattern-directory/patterns',
'/wp/v2/media',
'/wp/v2/media/(?P<id>[\\d]+)',
Expand Down
21 changes: 21 additions & 0 deletions tests/qunit/fixtures/wp-api-generated.js
Expand Up @@ -10453,6 +10453,27 @@ mockedApiResponse.Schema = {
]
}
},
"/wp/v2/pattern-directory/categories": {
"namespace": "wp/v2",
"methods": [
"GET"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": []
}
],
"_links": {
"self": [
{
"href": "http://example.org/index.php?rest_route=/wp/v2/pattern-directory/categories"
}
]
}
},
"/wp/v2/pattern-directory/patterns": {
"namespace": "wp/v2",
"methods": [
Expand Down