Completed
Push — add/purcases-package ( c4df86 )
by
unknown
31:35 queued 23:24
created

Purchases   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 5.88 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 3
loc 51
rs 10
c 0
b 0
f 0
wmc 8
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 10 2
B get_from_wpcom() 3 24 6

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
 * A utility class that helps us determine what purchases a site has made.
4
 *
5
 * @package automattic/jetpack-purchases
6
 */
7
8
namespace Automattic\Jetpack;
9
10
use Automattic\Jetpack\Connection\Client;
11
12
/**
13
 * Class Automattic\Jetpack\Purchases
14
 *
15
 * Contains utilities for determining what kind of purchases (plans and products) a site has made.
16
 */
17
class Purchases {
18
19
	const OPTION_CACHE = 'jetpack_purchases';
20
21
	/**
22
	 * Return the purchases a site has made.
23
	 *
24
	 * @return mixed|false
25
	 */
26
	public function get() {
27
		// Gets back all the purchases that site has made...
28
		$purchases = get_option( self::OPTION_CACHE, false );
29
30
		if ( $purchases ) {
31
			return $purchases;
32
		}
33
34
		return $this->get_from_wpcom();
35
	}
36
37
	/**
38
	 * Fetches the sites purchases from WP.com and caches them in an option.
39
	 *
40
	 * @return bool|mixed
41
	 */
42
	public function get_from_wpcom() {
43
44
		$request  = sprintf( '/sites/%d/purchases', \Jetpack_Options::get_option( 'id' ) );
45
		$response = Client::wpcom_json_api_request_as_blog( $request, '1.1', array( 'owner' => 'site' ) );
46
47
		// Bail if there was an error or malformed response.
48 View Code Duplication
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
49
			return false;
50
		}
51
52
		$body = wp_remote_retrieve_body( $response );
53
		if ( is_wp_error( $body ) ) {
54
			return false;
55
		}
56
		// Decode the results.
57
		$results = json_decode( $body, true );
58
59
		// Bail if there were no results or plan details returned.
60
		if ( ! is_array( $results ) ) {
61
			return false;
62
		}
63
		update_option( self::OPTION_CACHE, $results );
64
		return $results;
65
	}
66
67
}
68