-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remote.php
133 lines (110 loc) · 3.08 KB
/
Remote.php
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php
/**
* Handles 3rd party API.
*/
declare(strict_types=1);
namespace Remote_Users\Utils;
/**
* Class to handle 3rd part API.
*/
class Remote
{
/**
* 3rd party endpoint URL.
*/
private const ENDPOINT = 'https://jsonplaceholder.typicode.com/users/';
/**
* Transient key.
*/
private const TRANS_KEY = 'vg-remote-users';
/**
* Users list.
*
* Return the users list with success flag.
*
* @return array Users list.
*/
public function users(): array
{
$users = get_transient(self::TRANS_KEY) ?: $this->fetchUsersApi();
return $users;
}
/**
* Transient key.
*
* Return the transient key.
*
* @return string Transient key.
*/
public function transKey(): string
{
return self::TRANS_KEY;
}
/**
* Build users list.
*
* Fetches users from 3rd party.
*
* @return array Users list with success flag.
*/
private function fetchUsersApi(): array
{
$data = [ 'users' => [], 'is_success' => false ];
$headResponse = wp_safe_remote_head(self::ENDPOINT);
$remainingLimit = wp_remote_retrieve_header(
$headResponse,
'x-ratelimit-remaining'
);
/*
* Fetch header before getting body to check quota availability.
*/
if (
200 === wp_remote_retrieve_response_code($headResponse) &&
(int) $remainingLimit > 0
) {
$getResponse = wp_safe_remote_get(self::ENDPOINT);
if (! is_wp_error($getResponse)) {
$data['is_success'] = true;
}
if (200 === wp_remote_retrieve_response_code($getResponse)) {
$getAge = (int) wp_remote_retrieve_header(
$headResponse,
'age'
);
$getCacheCtl = wp_remote_retrieve_header(
$headResponse,
'cache-control'
);
$usersJsonStr = wp_remote_retrieve_body($getResponse);
$data['users'] = json_decode($usersJsonStr);
$this->setTransient($data, $getCacheCtl, $getAge);
}
}
return $data;
}
/**
* Set transient.
*
* Set transient by calculating expires time using header cache tags.
*
* @param array $data Data i.e. users list to be stored
* @param string $cacheCtl String extracted from cache control.
* @param int $age Age of the cached request in seconds.
*
* @return void
*/
private function setTransient(array $data, string $cacheCtl, int $age): void
{
$timeRemaining = HOUR_IN_SECONDS; //Default transient expiry.
$reg = '/max-age=(\d+)/';
preg_match($reg, $cacheCtl, $getMaxAge);
$diffTime = (int) $getMaxAge[1] - (int) $age;
if (
isset($getMaxAge[1]) &&
$diffTime > 0
) {
$timeRemaining = $diffTime;
}
set_transient(self::TRANS_KEY, $data, $timeRemaining);
}
}