Skip to content

Commit

Permalink
Code Quality: Move prepare_links() to its own method in taxonomies …
Browse files Browse the repository at this point in the history
…controller (#12569)
  • Loading branch information
spacedmonkey authored Nov 1, 2022
1 parent 4728f26 commit 1d25bbe
Showing 1 changed file with 42 additions and 17 deletions.
59 changes: 42 additions & 17 deletions includes/REST_API/Stories_Taxonomies_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@

/**
* Stories_Taxonomies_Controller class.
*
* @phpstan-import-type Links from \Google\Web_Stories\REST_API\Stories_Base_Controller
*/
class Stories_Taxonomies_Controller extends WP_REST_Taxonomies_Controller implements Service, Delayed, Registerable {
/**
Expand All @@ -61,29 +63,52 @@ public function __construct() {
* @return WP_REST_Response Response object.
*/
public function prepare_item_for_response( $taxonomy, $request ): WP_REST_Response {
$response = parent::prepare_item_for_response( $taxonomy, $request );
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
$controller = $taxonomy->get_rest_controller();

if ( ! $controller ) {
return $response;
}

$namespace = method_exists( $controller, 'get_namespace' ) ? $controller->get_namespace() : 'wp/v2';
$old_response = parent::prepare_item_for_response( $taxonomy, $request );

$response->remove_link( 'https://api.w.org/items' );
$response->add_links(
[
'https://api.w.org/items' => [
'href' => rest_url( sprintf( '%s/%s', $namespace, $base ) ),
],
]
);
/**
* Response data.
*
* @var array<string,mixed> $data
*/
$data = $old_response->get_data();
/**
* Response object.
*
* @var WP_REST_Response $response
*/
$response = rest_ensure_response( $data );
$response->add_links( $this->prepare_links( $taxonomy ) );

/** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php */
return apply_filters( 'rest_prepare_taxonomy', $response, $taxonomy, $request );
}

/**
* Prepares links for the request.
*
* @since 1.27.0
*
* @param WP_Taxonomy $taxonomy The taxonomy.
* @return array Links for the given taxonomy.
*
* @phpstan-return Links
*/
protected function prepare_links( $taxonomy ): array {
$controller = $taxonomy->get_rest_controller();
// TODO: Remove get_namespace when WP 5.9, min requirements.
$namespace = $controller && method_exists( $controller, 'get_namespace' ) ? $controller->get_namespace() : 'wp/v2';
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;

return [
'collection' => [
'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
],
'https://api.w.org/items' => [
'href' => rest_url( sprintf( '%s/%s', $namespace, $base ) ),
],
];
}

/**
* Retrieves all public taxonomies.
*
Expand Down

0 comments on commit 1d25bbe

Please sign in to comment.