class-base.php
1.45 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
<?php
declare( strict_types=1 );
namespace LearnDash\Hub\Framework;
use LearnDash\Hub\Traits\License;
/**
* This is the base class, every object should extend this.
*
* Class Base
*
* @package LearnDash\Hub
*/
class Base {
use License;
/**
* Export the class properties as array format.
*
* @return array
*/
public function to_array(): array {
return get_object_vars( $this );
}
/**
* Trigger a request to API server.
*
* @param string $endpoint The endpoint, as relative URL.
* @param string $method The method, GET OR POST.
* @param array $args The body args.
*
* @return array|mixed|\WP_Error
*/
protected function do_api_request( string $endpoint, string $method = 'GET', array $args = array() ) {
$base = LICENSING_SITE . '/wp-json/' . BASE_REST;
$response = wp_remote_request(
$base . $endpoint,
array(
'method' => $method,
'headers' => $this->get_auth_headers(),
'body' => $args,
)
);
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( 'rest_forbidden' === $body['code'] ) {
$body['message'] = __( 'Your license is invalid', 'learndash-hub' );
}
return new \WP_Error( $body['code'], $body['message'] );
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( ! is_array( $data ) ) {
// fail-safe.
$data = array();
}
return $data;
}
}