Completed
Push — master ( 1b71c1...8e6ca3 )
by Mike
09:47
created

WC_Webhook::build_payload()   C

Complexity

Conditions 9
Paths 8

Size

Total Lines 64
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 9
eloc 35
nc 8
nop 1
dl 0
loc 64
rs 6.5449
c 1
b 0
f 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit; // Exit if accessed directly
5
}
6
7
/**
8
 * WooCommerce Webhook class.
9
 *
10
 * This class handles storing and retrieving webhook data from the associated.
11
 * `shop_webhook` custom post type, as well as delivery logs from the `webhook_delivery`.
12
 * comment type.
13
 *
14
 * Webhooks are enqueued to their associated actions, delivered, and logged.
15
 *
16
 * @author      WooThemes
17
 * @category    Webhooks
18
 * @package     WooCommerce/Webhooks
19
 * @since       2.2
20
 */
21
class WC_Webhook {
22
23
	/** @var int webhook ID (post ID) */
24
	public $id;
25
26
	/**
27
	 * Setup webhook & load post data.
28
	 *
29
	 * @since 2.2
30
	 * @param string|int $id
31
	 */
32
	public function __construct( $id ) {
33
34
		$id = absint( $id );
35
36
		if ( ! $id ) {
37
			return;
38
		}
39
40
		$this->id = $id;
41
		$this->post_data = get_post( $id );
42
	}
43
44
45
	/**
46
	 * Magic isset as a wrapper around metadata_exists().
47
	 *
48
	 * @since 2.2
49
	 * @param string $key
50
	 * @return bool true if $key isset, false otherwise
51
	 */
52
	public function __isset( $key ) {
53
		if ( ! $this->id ) {
54
			return false;
55
		}
56
		return metadata_exists( 'post', $this->id, '_' . $key );
57
	}
58
59
60
	/**
61
	 * Magic get, wraps get_post_meta() for all keys except $status.
62
	 *
63
	 * @since 2.2
64
	 * @param string $key
65
	 * @return mixed value
66
	 */
67
	public function __get( $key ) {
68
69
		if ( 'status' === $key ) {
70
			$value = $this->get_status();
71
		} else {
72
			$value = get_post_meta( $this->id, '_' . $key, true );
73
		}
74
75
		return $value;
76
	}
77
78
79
	/**
80
	 * Enqueue the hooks associated with the webhook.
81
	 *
82
	 * @since 2.2
83
	 */
84
	public function enqueue() {
85
		$hooks = $this->get_hooks();
86
		$url   = $this->get_delivery_url();
87
88
		if ( is_array( $hooks ) && ! empty( $url ) ) {
89
			foreach ( $hooks as $hook ) {
90
				add_action( $hook, array( $this, 'process' ) );
91
			}
92
		}
93
	}
94
95
96
	/**
97
	 * Process the webhook for delivery by verifying that it should be delivered.
98
	 * and scheduling the delivery (in the background by default, or immediately).
99
	 *
100
	 * @since 2.2
101
	 * @param mixed $arg the first argument provided from the associated hooks
102
	 */
103
	public function process( $arg ) {
104
105
		// verify that webhook should be processed for delivery
106
		if ( ! $this->should_deliver( $arg ) ) {
107
			return;
108
		}
109
110
		// webhooks are processed in the background by default
111
		// so as to avoid delays or failures in delivery from affecting the
112
		// user who triggered it
113
		if ( apply_filters( 'woocommerce_webhook_deliver_async', true, $this, $arg ) ) {
114
115
			// deliver in background
116
			wp_schedule_single_event( time(), 'woocommerce_deliver_webhook_async', array( $this->id, $arg ) );
117
118
		} else {
119
120
			// deliver immediately
121
			$this->deliver( $arg );
122
		}
123
	}
124
125
	/**
126
	 * Helper to check if the webhook should be delivered, as some hooks.
127
	 * (like `wp_trash_post`) will fire for every post type, not just ours.
128
	 *
129
	 * @since 2.2
130
	 * @param mixed $arg first hook argument
131
	 * @return bool true if webhook should be delivered, false otherwise
132
	 */
133
	private function should_deliver( $arg ) {
134
		$should_deliver = true;
135
		$current_action = current_action();
136
137
		// only active webhooks can be delivered
138
		if ( 'active' != $this->get_status() ) {
139
			$should_deliver = false;
140
141
		// only deliver deleted event for coupons, orders, and products
142
		} elseif ( 'delete_post' === $current_action && ! in_array( $GLOBALS['post_type'], array( 'shop_coupon', 'shop_order', 'product' ) ) ) {
143
			$should_deliver = false;
144
145
		} elseif ( 'delete_user' == $current_action ) {
146
			$user = get_userdata( absint( $arg ) );
147
148
			// only deliver deleted customer event for users with customer role
149
			if ( ! $user || ! in_array( 'customer', (array) $user->roles ) ) {
150
				$should_deliver = false;
151
			}
152
153
		// check if the custom order type has chosen to exclude order webhooks from triggering along with its own webhooks.
154
		} elseif ( 'order' == $this->get_resource() && ! in_array( get_post_type( absint( $arg ) ), wc_get_order_types( 'order-webhooks' ) ) ) {
155
			$should_deliver = false;
156
157
		} elseif ( 0 === strpos( $current_action, 'woocommerce_process_shop' ) || 0 === strpos( $current_action, 'woocommerce_process_product' ) ) {
158
			// the `woocommerce_process_shop_*` and `woocommerce_process_product_*` hooks
159
			// fire for create and update of products and orders, so check the post
160
			// creation date to determine the actual event
161
			$resource = get_post( absint( $arg ) );
162
163
			// a resource is considered created when the hook is executed within 10 seconds of the post creation date
164
			$resource_created = ( ( time() - 10 ) <= strtotime( $resource->post_date_gmt ) );
165
166
			if ( 'created' == $this->get_event() && ! $resource_created ) {
167
				$should_deliver = false;
168
			} elseif ( 'updated' == $this->get_event() && $resource_created ) {
169
				$should_deliver = false;
170
			}
171
		}
172
173
		/*
174
		 * Let other plugins intercept deliver for some messages queue like rabbit/zeromq
175
		 */
176
		return apply_filters( 'woocommerce_webhook_should_deliver', $should_deliver, $this, $arg );
177
	}
178
179
180
	/**
181
	 * Deliver the webhook payload using wp_safe_remote_request().
182
	 *
183
	 * @since 2.2
184
	 * @param mixed $arg First hook argument.
185
	 */
186
	public function deliver( $arg ) {
187
188
		$payload = $this->build_payload( $arg );
189
190
		// Setup request args.
191
		$http_args = array(
192
			'method'      => 'POST',
193
			'timeout'     => MINUTE_IN_SECONDS,
194
			'redirection' => 0,
195
			'httpversion' => '1.0',
196
			'blocking'    => true,
197
			'user-agent'  => sprintf( 'WooCommerce/%s Hookshot (WordPress/%s)', WC_VERSION, $GLOBALS['wp_version'] ),
198
			'body'        => trim( json_encode( $payload ) ),
199
			'headers'     => array( 'Content-Type' => 'application/json' ),
200
			'cookies'     => array(),
201
		);
202
203
		$http_args = apply_filters( 'woocommerce_webhook_http_args', $http_args, $arg, $this->id );
204
205
		// Add custom headers.
206
		$http_args['headers']['X-WC-Webhook-Source']      = home_url( '/' ); // Since 2.6.0.
207
		$http_args['headers']['X-WC-Webhook-Topic']       = $this->get_topic();
208
		$http_args['headers']['X-WC-Webhook-Resource']    = $this->get_resource();
209
		$http_args['headers']['X-WC-Webhook-Event']       = $this->get_event();
210
		$http_args['headers']['X-WC-Webhook-Signature']   = $this->generate_signature( $http_args['body'] );
211
		$http_args['headers']['X-WC-Webhook-ID']          = $this->id;
212
		$http_args['headers']['X-WC-Webhook-Delivery-ID'] = $delivery_id = $this->get_new_delivery_id();
213
214
		$start_time = microtime( true );
215
216
		// Webhook away!
217
		$response = wp_safe_remote_request( $this->get_delivery_url(), $http_args );
218
219
		$duration = round( microtime( true ) - $start_time, 5 );
220
221
		$this->log_delivery( $delivery_id, $http_args, $response, $duration );
222
223
		do_action( 'woocommerce_webhook_delivery', $http_args, $response, $duration, $arg, $this->id );
224
	}
225
226
227
	/**
228
	 * Build the payload data for the webhook.
229
	 *
230
	 * @since 2.2
231
	 * @param mixed $resource_id first hook argument, typically the resource ID
232
	 * @return mixed payload data
233
	 */
234
	private function build_payload( $resource_id ) {
235
236
		// build the payload with the same user context as the user who created
237
		// the webhook -- this avoids permission errors as background processing
238
		// runs with no user context
239
		$current_user = get_current_user_id();
240
		wp_set_current_user( $this->get_user_id() );
241
242
		$resource = $this->get_resource();
243
		$event    = $this->get_event();
244
245
		// if a resource has been deleted, just include the ID
246
		if ( 'deleted' == $event ) {
247
248
			$payload = array(
249
				'id' => $resource_id,
250
			);
251
252
		} else {
253
254
			// include & load API classes
255
			WC()->api->includes();
256
			WC()->api->register_resources( new WC_API_Server( '/' ) );
257
258
			switch( $resource ) {
259
260
				case 'coupon':
261
					$payload = WC()->api->WC_API_Coupons->get_coupon( $resource_id );
262
					break;
263
264
				case 'customer':
265
					$payload = WC()->api->WC_API_Customers->get_customer( $resource_id );
266
					break;
267
268
				case 'order':
269
					$payload = WC()->api->WC_API_Orders->get_order( $resource_id );
270
					break;
271
272
				case 'product':
273
					// bulk and quick edit action hooks return a product object instead of an ID
274
					if ( 'updated' === $event && is_a( $resource_id, 'WC_Product' ) ) {
275
						$resource_id = $resource_id->get_id();
276
					}
277
					$payload = WC()->api->WC_API_Products->get_product( $resource_id );
278
					break;
279
280
				// custom topics include the first hook argument
281
				case 'action':
282
					$payload = array(
283
						'action' => current( $this->get_hooks() ),
284
						'arg'    => $resource_id,
285
					);
286
					break;
287
288
				default:
289
					$payload = array();
290
			}
291
		}
292
293
		// restore the current user
294
		wp_set_current_user( $current_user );
295
296
		return apply_filters( 'woocommerce_webhook_payload', $payload, $resource, $resource_id, $this->id );
297
	}
298
299
300
	/**
301
	 * Generate a base64-encoded HMAC-SHA256 signature of the payload body so the.
302
	 * recipient can verify the authenticity of the webhook. Note that the signature.
303
	 * is calculated after the body has already been encoded (JSON by default).
304
	 *
305
	 * @since 2.2
306
	 * @param string $payload payload data to hash
307
	 * @return string hash
308
	 */
309
	public function generate_signature( $payload ) {
310
311
		$hash_algo = apply_filters( 'woocommerce_webhook_hash_algorithm', 'sha256', $payload, $this->id );
312
313
		return base64_encode( hash_hmac( $hash_algo, $payload, $this->get_secret(), true ) );
314
	}
315
316
317
	/**
318
	 * Create a new comment for log the delivery request/response and.
319
	 * return the ID for inclusion in the webhook request.
320
	 *
321
	 * @since 2.2
322
	 * @return int delivery (comment) ID
323
	 */
324
	public function get_new_delivery_id() {
325
326
		$comment_data = apply_filters( 'woocommerce_new_webhook_delivery_data', array(
327
			'comment_author'       => __( 'WooCommerce', 'woocommerce' ),
328
			'comment_author_email' => sanitize_email( sprintf( '%s@%s', strtolower( __( 'WooCommerce', 'woocommerce' ) ), isset( $_SERVER['HTTP_HOST'] ) ? str_replace( 'www.', '', $_SERVER['HTTP_HOST'] ) : 'noreply.com' ) ),
329
			'comment_post_ID'      => $this->id,
330
			'comment_agent'        => 'WooCommerce Hookshot',
331
			'comment_type'         => 'webhook_delivery',
332
			'comment_parent'       => 0,
333
			'comment_approved'     => 1,
334
		), $this->id );
335
336
		$comment_id = wp_insert_comment( $comment_data );
337
338
		return $comment_id;
339
	}
340
341
342
	/**
343
	 * Log the delivery request/response.
344
	 *
345
	 * @since 2.2
346
	 * @param int $delivery_id previously created comment ID
347
	 * @param array $request request data
348
	 * @param array|WP_Error $response response data
349
	 * @param float $duration request duration
350
	 */
351
	public function log_delivery( $delivery_id, $request, $response, $duration ) {
352
353
		// save request data
354
		add_comment_meta( $delivery_id, '_request_method', $request['method'] );
355
		add_comment_meta( $delivery_id, '_request_headers', array_merge( array( 'User-Agent' => $request['user-agent'] ), $request['headers'] ) );
356
		add_comment_meta( $delivery_id, '_request_body', $request['body'] );
357
358
		// parse response
359
		if ( is_wp_error( $response ) ) {
360
			$response_code    = $response->get_error_code();
361
			$response_message = $response->get_error_message();
362
			$response_headers = array();
363
			$response_body    = '';
364
365
		} else {
366
			$response_code    = wp_remote_retrieve_response_code( $response );
367
			$response_message = wp_remote_retrieve_response_message( $response );
368
			$response_headers = wp_remote_retrieve_headers( $response );
369
			$response_body    = wp_remote_retrieve_body( $response );
370
		}
371
372
		// save response data
373
		add_comment_meta( $delivery_id, '_response_code', $response_code );
374
		add_comment_meta( $delivery_id, '_response_message', $response_message );
375
		add_comment_meta( $delivery_id, '_response_headers', $response_headers );
376
		add_comment_meta( $delivery_id, '_response_body', $response_body );
377
378
		// save duration
379
		add_comment_meta( $delivery_id, '_duration', $duration );
380
381
		// set a summary for quick display
382
		$args = array(
383
			'comment_ID' => $delivery_id,
384
			'comment_content' => sprintf( 'HTTP %s %s: %s', $response_code, $response_message, $response_body ),
385
		);
386
387
		wp_update_comment( $args );
388
389
		// track failures
390
		if ( intval( $response_code ) >= 200 && intval( $response_code ) < 300 ) {
391
			delete_post_meta( $this->id, '_failure_count' );
392
		} else {
393
			$this->failed_delivery();
394
		}
395
396
		// keep the 25 most recent delivery logs
397
		$log = wp_count_comments( $this->id );
398
		if ( $log->total_comments > apply_filters( 'woocommerce_max_webhook_delivery_logs', 25 ) ) {
399
			global $wpdb;
400
401
			$comment_id = $wpdb->get_var( $wpdb->prepare( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d ORDER BY comment_date_gmt ASC LIMIT 1", $this->id ) );
402
403
			if ( $comment_id ) {
404
				wp_delete_comment( $comment_id, true );
405
			}
406
		}
407
	}
408
409
	/**
410
	 * Track consecutive delivery failures and automatically disable the webhook.
411
	 * if more than 5 consecutive failures occur. A failure is defined as a.
412
	 * non-2xx response.
413
	 *
414
	 * @since 2.2
415
	 */
416
	private function failed_delivery() {
417
418
		$failures = $this->get_failure_count();
419
420
		if ( $failures > apply_filters( 'woocommerce_max_webhook_delivery_failures', 5 ) ) {
421
422
			$this->update_status( 'disabled' );
423
424
		} else {
425
426
			update_post_meta( $this->id, '_failure_count', ++$failures );
427
		}
428
	}
429
430
431
	/**
432
	 * Get the delivery logs for this webhook.
433
	 *
434
	 * @since 2.2
435
	 * @return array
436
	 */
437
	public function get_delivery_logs() {
438
439
		$args = array(
440
			'post_id' => $this->id,
441
			'status'  => 'approve',
442
			'type'    => 'webhook_delivery',
443
		);
444
445
		remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 );
446
447
		$logs = get_comments( $args );
448
449
		add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 );
450
451
		$delivery_logs = array();
452
453
		foreach ( $logs as $log ) {
454
455
			$log = $this->get_delivery_log( $log->comment_ID );
456
457
			$delivery_logs[] = ( ! empty( $log )  ? $log : array() );
458
		}
459
460
		return $delivery_logs;
461
	}
462
463
464
	/**
465
	 * Get the delivery log specified by the ID. The delivery log includes:
466
	 *
467
	 * + duration
468
	 * + summary
469
	 * + request method/url
470
	 * + request headers/body
471
	 * + response code/message/headers/body
472
	 *
473
	 * @since 2.2
474
	 * @param int $delivery_id
475
	 * @return bool|array false if invalid delivery ID, array of log data otherwise
476
	 */
477
	public function get_delivery_log( $delivery_id ) {
478
479
		$log = get_comment( $delivery_id );
480
481
		// valid comment and ensure delivery log belongs to this webhook
482
		if ( is_null( $log ) || $log->comment_post_ID != $this->id ) {
483
			return false;
484
		}
485
486
		$delivery_log = array(
487
			'id'               => intval( $delivery_id ),
488
			'duration'         => get_comment_meta( $delivery_id, '_duration', true ),
489
			'summary'          => $log->comment_content,
490
			'request_method'   => get_comment_meta( $delivery_id, '_request_method', true ),
491
			'request_url'      => $this->get_delivery_url(),
492
			'request_headers'  => get_comment_meta( $delivery_id, '_request_headers', true ),
493
			'request_body'     => get_comment_meta( $delivery_id, '_request_body', true ),
494
			'response_code'    => get_comment_meta( $delivery_id, '_response_code', true ),
495
			'response_message' => get_comment_meta( $delivery_id, '_response_message', true ),
496
			'response_headers' => get_comment_meta( $delivery_id, '_response_headers', true ),
497
			'response_body'    => get_comment_meta( $delivery_id, '_response_body', true ),
498
			'comment'          => $log,
499
		);
500
501
		return apply_filters( 'woocommerce_webhook_delivery_log', $delivery_log, $delivery_id, $this->id );
502
	}
503
504
	/**
505
	 * Set the webhook topic and associated hooks. The topic resource & event.
506
	 * are also saved separately.
507
	 *
508
	 * @since 2.2
509
	 * @param string $topic
510
	 */
511
	public function set_topic( $topic ) {
512
513
		$topic = strtolower( $topic );
514
515
		list( $resource, $event ) = explode( '.', $topic );
516
517
		update_post_meta( $this->id, '_topic', $topic );
518
		update_post_meta( $this->id, '_resource', $resource );
519
		update_post_meta( $this->id, '_event', $event );
520
521
		// custom topics are mapped to a single hook
522
		if ( 'action' === $resource ) {
523
524
			update_post_meta( $this->id, '_hooks', array( $event ) );
525
526
		} else {
527
528
			// API topics have multiple hooks
529
			update_post_meta( $this->id, '_hooks', $this->get_topic_hooks( $topic ) );
530
		}
531
	}
532
533
	/**
534
	 * Get the associated hook names for a topic.
535
	 *
536
	 * @since 2.2
537
	 * @param string $topic
538
	 * @return array hook names
539
	 */
540
	private function get_topic_hooks( $topic ) {
541
542
		$topic_hooks = array(
543
			'coupon.created' => array(
544
				'woocommerce_process_shop_coupon_meta',
545
				'woocommerce_api_create_coupon',
546
			),
547
			'coupon.updated' => array(
548
				'woocommerce_process_shop_coupon_meta',
549
				'woocommerce_api_edit_coupon',
550
			),
551
			'coupon.deleted' => array(
552
				'wp_trash_post',
553
			),
554
			'customer.created' => array(
555
				'user_register',
556
				'woocommerce_created_customer',
557
				'woocommerce_api_create_customer'
558
			),
559
			'customer.updated' => array(
560
				'profile_update',
561
				'woocommerce_api_edit_customer',
562
				'woocommerce_customer_save_address',
563
			),
564
			'customer.deleted' => array(
565
				'delete_user',
566
			),
567
			'order.created'    => array(
568
				'woocommerce_checkout_order_processed',
569
				'woocommerce_process_shop_order_meta',
570
				'woocommerce_api_create_order',
571
			),
572
			'order.updated' => array(
573
				'woocommerce_process_shop_order_meta',
574
				'woocommerce_api_edit_order',
575
				'woocommerce_order_edit_status',
576
				'woocommerce_order_status_changed'
577
			),
578
			'order.deleted' => array(
579
				'wp_trash_post',
580
			),
581
			'product.created' => array(
582
				'woocommerce_process_product_meta',
583
				'woocommerce_api_create_product',
584
			),
585
			'product.updated' => array(
586
				'woocommerce_process_product_meta',
587
				'woocommerce_api_edit_product',
588
				'woocommerce_product_quick_edit_save',
589
				'woocommerce_product_bulk_edit_save',
590
			),
591
			'product.deleted' => array(
592
				'wp_trash_post',
593
			),
594
		);
595
596
		$topic_hooks = apply_filters( 'woocommerce_webhook_topic_hooks', $topic_hooks, $this );
597
598
		return isset( $topic_hooks[ $topic ] ) ? $topic_hooks[ $topic ] : array();
599
	}
600
601
	/**
602
	 * Send a test ping to the delivery URL, sent when the webhook is first created.
603
	 *
604
	 * @since 2.2
605
	 * @return bool|WP_Error
606
	 */
607
	public function deliver_ping() {
608
		$args = array(
609
			'user-agent' => sprintf( 'WooCommerce/%s Hookshot (WordPress/%s)', WC_VERSION, $GLOBALS['wp_version'] ),
610
			'body'       => "webhook_id={$this->id}",
611
		);
612
613
		$test          = wp_safe_remote_post( $this->get_delivery_url(), $args );
614
		$response_code = wp_remote_retrieve_response_code( $test );
615
616
		if ( is_wp_error( $test ) ) {
617
			return new WP_Error( 'error', sprintf( __( 'Error: Delivery URL cannot be reached: %s', 'woocommerce' ), $test->get_error_message() ) );
618
		}
619
620
		if ( 200 !== $response_code ) {
621
			return new WP_Error( 'error', sprintf( __( 'Error: Delivery URL returned response code: %s', 'woocommerce' ), absint( $response_code ) ) );
622
		}
623
624
		return true;
625
	}
626
627
	/**
628
	 * Get the webhook status:
629
	 *
630
	 * + `active` - delivers payload.
631
	 * + `paused` - does not deliver payload, paused by admin.
632
	 * + `disabled` - does not delivery payload, paused automatically due to.
633
	 * consecutive failures.
634
	 *
635
	 * @since 2.2
636
	 * @return string status
637
	 */
638
	public function get_status() {
639
640 View Code Duplication
		switch ( $this->get_post_data()->post_status ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
641
642
			case 'publish':
643
				$status = 'active';
644
				break;
645
646
			case 'draft':
647
				$status = 'paused';
648
				break;
649
650
			case 'pending':
651
				$status = 'disabled';
652
				break;
653
654
			default:
655
				$status = 'paused';
656
		}
657
658
		return apply_filters( 'woocommerce_webhook_status', $status, $this->id );
659
	}
660
661
	/**
662
	 * Get the webhook i18n status.
663
	 *
664
	 * @return string
665
	 */
666
	public function get_i18n_status() {
667
		$status   = $this->get_status();
668
		$statuses = wc_get_webhook_statuses();
669
670
		return isset( $statuses[ $status ] ) ? $statuses[ $status ] : $status;
671
	}
672
673
	/**
674
	 * Update the webhook status, see get_status() for valid statuses.
675
	 *
676
	 * @since 2.2
677
	 * @param $status
678
	 */
679
	public function update_status( $status ) {
680
		global $wpdb;
681
682 View Code Duplication
		switch ( $status ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
683
684
			case 'active' :
685
				$post_status = 'publish';
686
				break;
687
688
			case 'paused' :
689
				$post_status = 'draft';
690
				break;
691
692
			case 'disabled' :
693
				$post_status = 'pending';
694
				break;
695
696
			default :
697
				$post_status = 'draft';
698
				break;
699
		}
700
701
		$wpdb->update( $wpdb->posts, array( 'post_status' => $post_status ), array( 'ID' => $this->id ) );
702
		clean_post_cache( $this->id );
703
	}
704
705
	/**
706
	 * Set the delivery URL.
707
	 *
708
	 * @since 2.2
709
	 * @param string $url
710
	 */
711
	public function set_delivery_url( $url ) {
712
		if ( update_post_meta( $this->id, '_delivery_url', esc_url_raw( $url, array( 'http', 'https' ) ) ) ) {
713
			update_post_meta( $this->id, '_webhook_pending_delivery', true );
714
		}
715
	}
716
717
	/**
718
	 * Get the delivery URL.
719
	 *
720
	 * @since 2.2
721
	 * @return string
722
	 */
723
	public function get_delivery_url() {
724
725
		return apply_filters( 'woocommerce_webhook_delivery_url', $this->delivery_url, $this->id );
726
	}
727
728
	/**
729
	 * Set the secret used for generating the HMAC-SHA256 signature.
730
	 *
731
	 * @since 2.2
732
	 * @param string $secret
733
	 */
734
	public function set_secret( $secret ) {
735
736
		update_post_meta( $this->id, '_secret', $secret );
737
	}
738
739
	/**
740
	 * Get the secret used for generating the HMAC-SHA256 signature.
741
	 *
742
	 * @since 2.2
743
	 * @return string
744
	 */
745
	public function get_secret() {
746
		return apply_filters( 'woocommerce_webhook_secret', $this->secret, $this->id );
747
	}
748
749
	/**
750
	 * Get the friendly name for the webhook.
751
	 *
752
	 * @since 2.2
753
	 * @return string
754
	 */
755
	public function get_name() {
756
		return apply_filters( 'woocommerce_webhook_name', $this->get_post_data()->post_title, $this->id );
757
	}
758
759
	/**
760
	 * Get the webhook topic, e.g. `order.created`.
761
	 *
762
	 * @since 2.2
763
	 * @return string
764
	 */
765
	public function get_topic() {
766
		return apply_filters( 'woocommerce_webhook_topic', $this->topic, $this->id );
767
	}
768
769
	/**
770
	 * Get the hook names for the webhook.
771
	 *
772
	 * @since 2.2
773
	 * @return array hook names
774
	 */
775
	public function get_hooks() {
776
		return apply_filters( 'woocommerce_webhook_hooks', $this->hooks, $this->id );
777
	}
778
779
	/**
780
	 * Get the resource for the webhook, e.g. `order`.
781
	 *
782
	 * @since 2.2
783
	 * @return string
784
	 */
785
	public function get_resource() {
786
		return apply_filters( 'woocommerce_webhook_resource', $this->resource, $this->id );
787
	}
788
789
	/**
790
	 * Get the event for the webhook, e.g. `created`.
791
	 *
792
	 * @since 2.2
793
	 * @return string
794
	 */
795
	public function get_event() {
796
		return apply_filters( 'woocommerce_webhook_event', $this->event, $this->id );
797
	}
798
799
	/**
800
	 * Get the failure count.
801
	 *
802
	 * @since 2.2
803
	 * @return int
804
	 */
805
	public function get_failure_count() {
806
		return intval( $this->failure_count );
807
	}
808
809
	/**
810
	 * Get the user ID for this webhook.
811
	 *
812
	 * @since 2.2
813
	 * @return int|string user ID
814
	 */
815
	public function get_user_id() {
816
		return $this->get_post_data()->post_author;
817
	}
818
819
	/**
820
	 * Get the post data for the webhook.
821
	 *
822
	 * @since 2.2
823
	 * @return null|WP_Post
824
	 */
825
	public function get_post_data() {
826
		return $this->post_data;
827
	}
828
829
}
830