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

Purchases::get_from_wpcom()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 24

Duplication

Lines 3
Ratio 12.5 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 0
dl 3
loc 24
rs 8.9137
c 0
b 0
f 0
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