WC_REST_Webhook_Deliveries_Controller   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 285
Duplicated Lines 25.96 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 74
loc 285
rs 10
c 0
b 0
f 0
wmc 20
lcom 1
cbo 2

9 Methods

Rating   Name   Duplication   Size   Complexity  
A register_routes() 23 23 1
A get_items_permissions_check() 7 7 2
A get_item_permissions_check() 9 9 3
A get_items() 18 18 4
B get_item() 0 19 5
B prepare_item_for_response() 0 27 2
A prepare_links() 17 17 1
B get_item_schema() 0 85 1
A get_collection_params() 0 5 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * REST API Webhooks controller
4
 *
5
 * Handles requests to the /webhooks/<webhook_id>/deliveries endpoint.
6
 *
7
 * @author   WooThemes
8
 * @category API
9
 * @package  WooCommerce/API
10
 * @since    2.6.0
11
 */
12
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * REST API Webhook Deliveries controller class.
19
 *
20
 * @package WooCommerce/API
21
 * @extends WC_REST_Controller
22
 */
23
class WC_REST_Webhook_Deliveries_Controller extends WC_REST_Controller {
24
25
	/**
26
	 * Endpoint namespace.
27
	 *
28
	 * @var string
29
	 */
30
	protected $namespace = 'wc/v1';
31
32
	/**
33
	 * Route base.
34
	 *
35
	 * @var string
36
	 */
37
	protected $rest_base = 'webhooks/(?P<webhook_id>[\d]+)/deliveries';
38
39
	/**
40
	 * Register the routes for webhook deliveries.
41
	 */
42 View Code Duplication
	public function register_routes() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
44
			array(
45
				'methods'             => WP_REST_Server::READABLE,
46
				'callback'            => array( $this, 'get_items' ),
47
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
48
				'args'                => $this->get_collection_params(),
49
			),
50
			'schema' => array( $this, 'get_public_item_schema' ),
51
		) );
52
53
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
54
			array(
55
				'methods'             => WP_REST_Server::READABLE,
56
				'callback'            => array( $this, 'get_item' ),
57
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
58
				'args'                => array(
59
					'context' => $this->get_context_param( array( 'default' => 'view' ) ),
60
				),
61
			),
62
			'schema' => array( $this, 'get_public_item_schema' ),
63
		) );
64
	}
65
66
	/**
67
	 * Check whether a given request has permission to read webhook deliveries.
68
	 *
69
	 * @param  WP_REST_Request $request Full details about the request.
70
	 * @return WP_Error|boolean
71
	 */
72 View Code Duplication
	public function get_items_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
73
		if ( ! wc_rest_check_post_permissions( 'shop_webhook', 'read' ) ) {
74
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
75
		}
76
77
		return true;
78
	}
79
80
	/**
81
	 * Check if a given request has access to read a webhook develivery.
82
	 *
83
	 * @param  WP_REST_Request $request Full details about the request.
84
	 * @return WP_Error|boolean
85
	 */
86 View Code Duplication
	public function get_item_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87
		$post = get_post( (int) $request['webhook_id'] );
88
89
		if ( $post && ! wc_rest_check_post_permissions( 'shop_webhook', 'read', $post->ID ) ) {
90
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
91
		}
92
93
		return true;
94
	}
95
96
	/**
97
	 * Get all webhook deliveries.
98
	 *
99
	 * @param WP_REST_Request $request
100
	 * @return array
101
	 */
102 View Code Duplication
	public function get_items( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
		$webhook = new WC_Webhook( (int) $request['webhook_id'] );
104
105
		if ( empty( $webhook->post_data->post_type ) || 'shop_webhook' !== $webhook->post_data->post_type ) {
106
			return new WP_Error( 'woocommerce_rest_webhook_invalid_id', __( 'Invalid webhook id.', 'woocommerce' ), array( 'status' => 404 ) );
107
		}
108
109
		$logs = $webhook->get_delivery_logs();
110
111
		$data = array();
112
		foreach ( $logs as $log ) {
113
			$delivery = $this->prepare_item_for_response( (object) $log, $request );
114
			$delivery = $this->prepare_response_for_collection( $delivery );
115
			$data[]   = $delivery;
116
		}
117
118
		return rest_ensure_response( $data );
119
	}
120
121
	/**
122
	 * Get a single webhook delivery.
123
	 *
124
	 * @param WP_REST_Request $request Full details about the request.
125
	 * @return WP_Error|WP_REST_Response
126
	 */
127
	public function get_item( $request ) {
128
		$id      = (int) $request['id'];
129
		$webhook = new WC_Webhook( (int) $request['webhook_id'] );
130
131
		if ( empty( $webhook->post_data->post_type ) || 'shop_webhook' !== $webhook->post_data->post_type ) {
132
			return new WP_Error( 'woocommerce_rest_webhook_invalid_id', __( 'Invalid webhook id.', 'woocommerce' ), array( 'status' => 404 ) );
133
		}
134
135
		$log = $webhook->get_delivery_log( $id );
136
137
		if ( empty( $id ) || empty( $log ) ) {
138
			return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource id.', 'woocommerce' ), array( 'status' => 404 ) );
139
		}
140
141
		$delivery = $this->prepare_item_for_response( (object) $log, $request );
142
		$response = rest_ensure_response( $delivery );
143
144
		return $response;
145
	}
146
147
	/**
148
	 * Prepare a single webhook delivery output for response.
149
	 *
150
	 * @param stdClass $log Delivery log object.
151
	 * @param WP_REST_Request $request Request object.
152
	 * @return WP_REST_Response $response Response data.
153
	 */
154
	public function prepare_item_for_response( $log, $request ) {
155
		$data = (array) $log;
156
157
		// Add timestamp.
158
		$data['date_created'] = wc_rest_prepare_date_response( $log->comment->comment_date_gmt );
159
160
		// Remove comment object.
161
		unset( $data['comment'] );
162
163
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
164
		$data    = $this->add_additional_fields_to_object( $data, $request );
165
		$data    = $this->filter_response_by_context( $data, $context );
166
167
		// Wrap the data in a response object.
168
		$response = rest_ensure_response( $data );
169
170
		$response->add_links( $this->prepare_links( $log ) );
171
172
		/**
173
		 * Filter webhook delivery object returned from the REST API.
174
		 *
175
		 * @param WP_REST_Response $response The response object.
176
		 * @param stdClass         $log      Delivery log object used to create response.
177
		 * @param WP_REST_Request  $request  Request object.
178
		 */
179
		return apply_filters( 'woocommerce_rest_prepare_webhook_delivery', $response, $log, $request );
180
	}
181
182
	/**
183
	 * Prepare links for the request.
184
	 *
185
	 * @param stdClass $log Delivery log object.
186
	 * @return array Links for the given webhook delivery.
187
	 */
188 View Code Duplication
	protected function prepare_links( $log ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
189
		$webhook_id = (int) $log->request_headers['X-WC-Webhook-ID'];
190
		$base       = str_replace( '(?P<webhook_id>[\d]+)', $webhook_id, $this->rest_base );
191
		$links      = array(
192
			'self' => array(
193
				'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $base, $log->id ) ),
194
			),
195
			'collection' => array(
196
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $base ) ),
197
			),
198
			'up' => array(
199
				'href' => rest_url( sprintf( '/%s/webhooks/%d', $this->namespace, $webhook_id ) ),
200
			),
201
		);
202
203
		return $links;
204
	}
205
206
	/**
207
	 * Get the Webhook's schema, conforming to JSON Schema.
208
	 *
209
	 * @return array
210
	 */
211
	public function get_item_schema() {
212
		$schema = array(
213
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
214
			'title'      => 'webhook_delivery',
215
			'type'       => 'object',
216
			'properties' => array(
217
				'id' => array(
218
					'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
219
					'type'        => 'integer',
220
					'context'     => array( 'view' ),
221
					'readonly'    => true,
222
				),
223
				'duration' => array(
224
					'description' => __( 'The delivery duration, in seconds.', 'woocommerce' ),
225
					'type'        => 'string',
226
					'context'     => array( 'view' ),
227
					'readonly'    => true,
228
				),
229
				'summary' => array(
230
					'description' => __( 'A friendly summary of the response including the HTTP response code, message, and body.', 'woocommerce' ),
231
					'type'        => 'string',
232
					'context'     => array( 'view' ),
233
					'readonly'    => true,
234
				),
235
				'request_url' => array(
236
					'description' => __( 'The URL where the webhook was delivered.', 'woocommerce' ),
237
					'type'        => 'string',
238
					'format'      => 'uri',
239
					'context'     => array( 'view' ),
240
					'readonly'    => true,
241
				),
242
				'request_headers' => array(
243
					'description' => __( 'The URL where the webhook was delivered.', 'woocommerce' ),
244
					'type'        => 'string',
245
					'format'      => 'uri',
246
					'context'     => array( 'view' ),
247
					'readonly'    => true,
248
				),
249
				'request_headers' => array(
250
					'description' => __( 'Request headers.', 'woocommerce' ),
251
					'type'        => 'array',
252
					'context'     => array( 'view' ),
253
					'readonly'    => true,
254
				),
255
				'request_body' => array(
256
					'description' => __( 'Request body.', 'woocommerce' ),
257
					'type'        => 'string',
258
					'context'     => array( 'view' ),
259
					'readonly'    => true,
260
				),
261
				'response_code' => array(
262
					'description' => __( 'The HTTP response code from the receiving server.', 'woocommerce' ),
263
					'type'        => 'string',
264
					'context'     => array( 'view' ),
265
					'readonly'    => true,
266
				),
267
				'response_message' => array(
268
					'description' => __( 'The HTTP response message from the receiving server.', 'woocommerce' ),
269
					'type'        => 'string',
270
					'context'     => array( 'view' ),
271
					'readonly'    => true,
272
				),
273
				'response_headers' => array(
274
					'description' => __( 'Array of the response headers from the receiving server.', 'woocommerce' ),
275
					'type'        => 'array',
276
					'context'     => array( 'view' ),
277
					'readonly'    => true,
278
				),
279
				'response_body' => array(
280
					'description' => __( 'The response body from the receiving server.', 'woocommerce' ),
281
					'type'        => 'string',
282
					'context'     => array( 'view' ),
283
					'readonly'    => true,
284
				),
285
				'date_created' => array(
286
					'description' => __( "The date the webhook delivery was logged, in the site's timezone.", 'woocommerce' ),
287
					'type'        => 'date-time',
288
					'context'     => array( 'view', 'edit' ),
289
					'readonly'    => true,
290
				),
291
			),
292
		);
293
294
		return $this->add_additional_fields_schema( $schema );
295
	}
296
297
	/**
298
	 * Get the query params for collections.
299
	 *
300
	 * @return array
301
	 */
302
	public function get_collection_params() {
303
		return array(
304
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
305
		);
306
	}
307
}
308