class-extensions.php
1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
namespace HM\BackUpWordPress;
/**
* Class Extensions
* @package HM\BackUpWordPress
*/
final class Extensions {
/**
* Contains the instantiated Extensions instance.
*
* @var Extensions $this->instance
*/
private static $instance;
/**
* Holds the root URL of the API.
*
* @var string
*/
protected $root_url = '';
/**
* Extensions constructor.
*
*/
private function __construct() {
$this->root_url = 'https://bwp.hmn.md/wp-json/wp/v2/';
}
private function __wakeup() {}
private function __clone() {}
/**
* Returns the *Singleton* instance of this class.
*
* @staticvar Extensions $instance The *Singleton* instances of this class.
*
* @return Extensions The *Singleton* instance.
*/
public static function get_instance() {
if ( ! ( self::$instance instanceof Extensions ) ) {
self::$instance = new Extensions();
}
return self::$instance;
}
/**
* Parses the body of the API response and returns it.
*
* @return array|bool|mixed|object
*/
public function get_edd_data() {
$response = $this->fetch( 'edd-downloads' );
if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
return false;
}
return json_decode( $response['body'] );
}
/**
* Makes a request to the JSON API or retrieves the cached response. Caches the response for one day.
*
* @param $endpoint
* @param int $ttl
*
* @return array|mixed|\WP_Error
*/
protected function fetch( $endpoint, $ttl = DAY_IN_SECONDS ) {
$request_url = $this->root_url . $endpoint;
$cache_key = md5( $request_url );
$cached = get_transient( 'bwp_' . $cache_key );
if ( $cached ) {
return $cached;
}
$response = wp_remote_get( $request_url );
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
return new \WP_Error( 'hmbkp-error', 'Unable to fetch API response' );
}
set_transient( 'bwp_' . $cache_key, $response, $ttl );
return $response;
}
}