This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 217
/
AbstractRoute.php
310 lines (272 loc) · 9.26 KB
/
AbstractRoute.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
namespace Automattic\WooCommerce\Blocks\StoreApi\Routes;
use Automattic\WooCommerce\Blocks\StoreApi\Schemas\AbstractSchema;
/**
* AbstractRoute class.
*
* @internal This API is used internally by Blocks--it is still in flux and may be subject to revisions.
*/
abstract class AbstractRoute implements RouteInterface {
/**
* Schema class instance.
*
* @var AbstractSchema
*/
protected $schema;
/**
* Constructor.
*
* @param AbstractSchema $schema Schema class for this route.
*/
public function __construct( AbstractSchema $schema ) {
$this->schema = $schema;
}
/**
* Get the namespace for this route.
*
* @return string
*/
public function get_namespace() {
return 'wc/store';
}
/**
* Get item schema properties.
*
* @return array
*/
public function get_item_schema() {
return $this->schema->get_item_schema();
}
/**
* Get the route response based on the type of request.
*
* @param \WP_REST_Request $request Request object.
* @return \WP_REST_Response
*/
public function get_response( \WP_REST_Request $request ) {
$response = null;
try {
if ( 'GET' !== $request->get_method() ) {
$this->check_nonce( $request );
}
switch ( $request->get_method() ) {
case 'POST':
$response = $this->get_route_post_response( $request );
break;
case 'PUT':
case 'PATCH':
$response = $this->get_route_update_response( $request );
break;
case 'DELETE':
$response = $this->get_route_delete_response( $request );
break;
default:
$response = $this->get_route_response( $request );
break;
}
} catch ( RouteException $error ) {
$response = $this->get_route_error_response( $error->getErrorCode(), $error->getMessage(), $error->getCode(), $error->getAdditionalData() );
} catch ( \Exception $error ) {
$response = $this->get_route_error_response( 'unknown_server_error', $error->getMessage(), 500 );
}
if ( is_wp_error( $response ) ) {
$response = $this->error_to_response( $response );
}
$response->header( 'X-WC-Store-API-Nonce', wp_create_nonce( 'wc_store_api' ) );
$response->header( 'X-WC-Store-API-Nonce-Timestamp', time() );
$response->header( 'X-WC-Store-API-User', get_current_user_id() );
return $response;
}
/**
* Converts an error to a response object. Based on \WP_REST_Server.
*
* @param WP_Error $error WP_Error instance.
* @return WP_REST_Response List of associative arrays with code and message keys.
*/
protected function error_to_response( $error ) {
$error_data = $error->get_error_data();
$status = isset( $error_data, $error_data['status'] ) ? $error_data['status'] : 500;
$errors = [];
foreach ( (array) $error->errors as $code => $messages ) {
foreach ( (array) $messages as $message ) {
$errors[] = array(
'code' => $code,
'message' => $message,
'data' => $error->get_error_data( $code ),
);
}
}
$data = array_shift( $errors );
if ( count( $errors ) ) {
$data['additional_errors'] = $errors;
}
return new \WP_REST_Response( $data, $status );
}
/**
* For non-GET endpoints, require and validate a nonce to prevent CSRF attacks.
*
* Nonces will mismatch if the logged in session cookie is different! If using a client to test, set this cookie
* to match the logged in cookie in your browser.
*
* @throws RouteException On error.
*
* @param \WP_REST_Request $request Request object.
*/
protected function check_nonce( \WP_REST_Request $request ) {
$nonce = $request->get_header( 'X-WC-Store-API-Nonce' );
if ( apply_filters( 'woocommerce_store_api_disable_nonce_check', false ) ) {
return;
}
if ( null === $nonce ) {
throw new RouteException( 'woocommerce_rest_missing_nonce', __( 'Missing the X-WC-Store-API-Nonce header. This endpoint requires a valid nonce.', 'woo-gutenberg-products-block' ), 401 );
}
$valid_nonce = wp_verify_nonce( $nonce, 'wc_store_api' );
if ( ! $valid_nonce ) {
throw new RouteException( 'woocommerce_rest_invalid_nonce', __( 'X-WC-Store-API-Nonce is invalid.', 'woo-gutenberg-products-block' ), 403 );
}
}
/**
* Get route response for GET requests.
*
* When implemented, should return a \WP_REST_Response.
*
* @throws RouteException On error.
* @param \WP_REST_Request $request Request object.
*/
protected function get_route_response( \WP_REST_Request $request ) {
throw new RouteException( 'woocommerce_rest_invalid_endpoint', __( 'Method not implemented', 'woo-gutenberg-products-block' ), 404 );
}
/**
* Get route response for POST requests.
*
* When implemented, should return a \WP_REST_Response.
*
* @throws RouteException On error.
* @param \WP_REST_Request $request Request object.
*/
protected function get_route_post_response( \WP_REST_Request $request ) {
throw new RouteException( 'woocommerce_rest_invalid_endpoint', __( 'Method not implemented', 'woo-gutenberg-products-block' ), 404 );
}
/**
* Get route response for PUT requests.
*
* When implemented, should return a \WP_REST_Response.
*
* @throws RouteException On error.
* @param \WP_REST_Request $request Request object.
*/
protected function get_route_update_response( \WP_REST_Request $request ) {
throw new RouteException( 'woocommerce_rest_invalid_endpoint', __( 'Method not implemented', 'woo-gutenberg-products-block' ), 404 );
}
/**
* Get route response for DELETE requests.
*
* When implemented, should return a \WP_REST_Response.
*
* @throws RouteException On error.
* @param \WP_REST_Request $request Request object.
*/
protected function get_route_delete_response( \WP_REST_Request $request ) {
throw new RouteException( 'woocommerce_rest_invalid_endpoint', __( 'Method not implemented', 'woo-gutenberg-products-block' ), 404 );
}
/**
* Get route response when something went wrong.
*
* @param string $error_code String based error code.
* @param string $error_message User facing error message.
* @param int $http_status_code HTTP status. Defaults to 500.
* @param array $additional_data Extra data (key value pairs) to expose in the error response.
* @return \WP_Error WP Error object.
*/
protected function get_route_error_response( $error_code, $error_message, $http_status_code = 500, $additional_data = [] ) {
return new \WP_Error( $error_code, $error_message, array_merge( $additional_data, [ 'status' => $http_status_code ] ) );
}
/**
* Prepare a single item for response.
*
* @param mixed $item Item to format to schema.
* @param \WP_REST_Request $request Request object.
* @return \WP_REST_Response $response Response data.
*/
public function prepare_item_for_response( $item, \WP_REST_Request $request ) {
$response = rest_ensure_response( $this->schema->get_item_response( $item ) );
$response->add_links( $this->prepare_links( $item, $request ) );
return $response;
}
/**
* Retrieves the context param.
*
* Ensures consistent descriptions between endpoints, and populates enum from schema.
*
* @param array $args Optional. Additional arguments for context parameter. Default empty array.
* @return array Context parameter details.
*/
protected function get_context_param( $args = array() ) {
$param_details = array(
'description' => __( 'Scope under which the request is made; determines fields present in response.', 'woo-gutenberg-products-block' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
'validate_callback' => 'rest_validate_request_arg',
);
$schema = $this->get_item_schema();
if ( empty( $schema['properties'] ) ) {
return array_merge( $param_details, $args );
}
$contexts = array();
foreach ( $schema['properties'] as $attributes ) {
if ( ! empty( $attributes['context'] ) ) {
$contexts = array_merge( $contexts, $attributes['context'] );
}
}
if ( ! empty( $contexts ) ) {
$param_details['enum'] = array_unique( $contexts );
rsort( $param_details['enum'] );
}
return array_merge( $param_details, $args );
}
/**
* Prepares a response for insertion into a collection.
*
* @param \WP_REST_Response $response Response object.
* @return array|mixed Response data, ready for insertion into collection data.
*/
protected function prepare_response_for_collection( \WP_REST_Response $response ) {
$data = (array) $response->get_data();
$server = rest_get_server();
$links = $server::get_compact_response_links( $response );
if ( ! empty( $links ) ) {
$data['_links'] = $links;
}
return $data;
}
/**
* Prepare links for the request.
*
* @param mixed $item Item to prepare.
* @param \WP_REST_Request $request Request object.
* @return array
*/
protected function prepare_links( $item, $request ) {
return [];
}
/**
* Retrieves the query params for the collections.
*
* @return array Query parameters for the collection.
*/
public function get_collection_params() {
return array(
'context' => $this->get_context_param(),
);
}
/**
* Makes the cart and sessions available to a route by loading them from core.
*/
protected function maybe_load_cart() {
if ( ! did_action( 'woocommerce_load_cart_from_session' ) && function_exists( 'wc_load_cart' ) ) {
include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
wc_load_cart();
}
}
}