Completed
Push — branch-8.7-built ( 50de0f...7a10d7 )
by Jeremy
32:57 queued 24:29
created

Jetpack_Tweetstorm_Helper   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 66
Duplicated Lines 18.18 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 0
dl 12
loc 66
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B gather() 0 40 8
A get_site_id() 12 12 4

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
 * Tweetstorm block and API helper.
4
 *
5
 * @package jetpack
6
 * @since 8.7.0
7
 */
8
9
use Automattic\Jetpack\Connection\Client;
10
use Automattic\Jetpack\Status;
11
/**
12
 * Class Jetpack_Tweetstorm_Helper
13
 *
14
 * @since 8.7.0
15
 */
16
class Jetpack_Tweetstorm_Helper {
17
	/**
18
	 * Gather the Tweetstorm.
19
	 *
20
	 * @param  string $url The tweet URL to gather from.
21
	 * @return mixed
22
	 */
23
	public static function gather( $url ) {
24
		if ( ( new Status() )->is_development_mode() ) {
25
			return new WP_Error(
26
				'dev_mode',
27
				__( 'Tweet unrolling is not available in development mode.', 'jetpack' )
28
			);
29
		}
30
31
		$site_id = self::get_site_id();
32
		if ( is_wp_error( $site_id ) ) {
33
			return $site_id;
34
		}
35
36
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
37
			if ( ! class_exists( 'WPCOM_Gather_Tweetstorm' ) ) {
38
				\jetpack_require_lib( 'gather-tweetstorm' );
39
			}
40
41
			return WPCOM_Gather_Tweetstorm::gather( $url );
42
		}
43
44
		$response = Client::wpcom_json_api_request_as_blog(
45
			sprintf( '/sites/%d/tweetstorm/gather?url=%s', $site_id, rawurlencode( $url ) ),
46
			2,
47
			array( 'headers' => array( 'content-type' => 'application/json' ) ),
48
			null,
49
			'wpcom'
50
		);
51
		if ( is_wp_error( $response ) ) {
52
			return $response;
53
		}
54
55
		$data = json_decode( wp_remote_retrieve_body( $response ) );
56
57
		if ( wp_remote_retrieve_response_code( $response ) >= 400 ) {
58
			return new WP_Error( $data->code, $data->message, $data->data );
59
		}
60
61
		return $data;
62
	}
63
64
	/**
65
	 * Get the WPCOM or self-hosted site ID.
66
	 *
67
	 * @return mixed
68
	 */
69 View Code Duplication
	public static function get_site_id() {
70
		$is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
71
		$site_id  = $is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
72
		if ( ! $site_id ) {
73
			return new WP_Error(
74
				'unavailable_site_id',
75
				__( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack' ),
76
				403
77
			);
78
		}
79
		return (int) $site_id;
80
	}
81
}
82