| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Core class used to access templates via the REST API before WordPress 7.2. |
| 5 |
* |
| 6 |
* This class extension exists to prevent a fatal error when a `null` template |
| 7 |
* reaches `prepare_item_for_response`, which reads and assigns properties on |
| 8 |
* it. Core's `update_item` can pass `null` there from either of its two |
| 9 |
* unchecked `get_block_template()` refetches: after writing an update, and on |
| 10 |
* its "revert to theme" path, which force-deletes the template's post before |
| 11 |
* checking that a theme or plugin version of the template exists. |
| 12 |
* |
| 13 |
* |
| 14 |
* @see WP_REST_Templates_Controller |
| 15 |
*/ |
| 16 |
class Gutenberg_REST_Templates_Controller_7_2 extends WP_REST_Templates_Controller { |
| 17 |
/** |
| 18 |
* Prepares a single template output for response. |
| 19 |
* |
| 20 |
* @since 5.8.0 |
| 21 |
* @since 7.2.0 Answers with an error response instead of a fatal error |
| 22 |
* when the template is `null`. |
| 23 |
* |
| 24 |
* @param WP_Block_Template|null $item Template instance. |
| 25 |
* @param WP_REST_Request $request Request object. |
| 26 |
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error when the template is `null`. |
| 27 |
*/ |
| 28 |
public function prepare_item_for_response( $item, $request ) { |
| 29 |
////////////////////////////// |
| 30 |
// START CORE MODIFICATIONS // |
| 31 |
////////////////////////////// |
| 32 |
/* |
| 33 |
* Core's `update_item` passes its `get_block_template()` refetches |
| 34 |
* here unchecked, both after writing an update and after deleting |
| 35 |
* the post on its revert path. Reading `$item->content` on `null` |
| 36 |
* is a fatal error, so answer with an error response instead. |
| 37 |
*/ |
| 38 |
if ( ! $item ) { |
| 39 |
return new WP_Error( 'rest_template_not_found', __( 'No templates exist with that id.' ), array( 'status' => 404 ) ); |
| 40 |
} |
| 41 |
////////////////////////////// |
| 42 |
// END CORE MODIFICATIONS // |
| 43 |
////////////////////////////// |
| 44 |
|
| 45 |
return parent::prepare_item_for_response( $item, $request ); |
| 46 |
} |
| 47 |
} |
| 48 |
|