-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrait-request.php
75 lines (60 loc) · 1.69 KB
/
trait-request.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
<?php
trait Request {
private array $response_cache = [];
private function base_request(
string $path,
string $method = 'GET',
?array $args = null,
bool $parse = true,
bool $return_headers = false
) {
if ( ! empty( $args['params'] ) ) {
$path .= '?' . http_build_query( $args['params'] );
}
$flat_headers = [];
foreach ( $args['headers'] ?? [] as $name => $value ) {
$flat_headers[] = "$name: $value";
}
$cache_key = md5( $path . $method . serialize( $flat_headers ) );
if ( isset( $this->response_cache[ $cache_key ] ) ) {
return $this->response_cache[ $cache_key ];
}
$ch = curl_init( $path );
if ( 'POST' === $method ) {
curl_setopt( $ch, CURLOPT_POST, 1 );
} else if ( 'DELETE' === $method ) {
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'DELETE' );
}
curl_setopt( $ch, CURLOPT_HTTPHEADER, $flat_headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
if ( $return_headers ) {
$headers = [];
curl_setopt( $ch, CURLOPT_HEADERFUNCTION, function( $curl, $header ) use ( &$headers ) {
$len = strlen( $header );
$header = explode( ':', $header, 2 );
if ( count( $header ) < 2 ) {
return $len;
}
$headers[ trim( $header[0] ) ] = trim( $header[1] );
return $len;
} );
}
$response = curl_exec( $ch );
curl_close( $ch );
if ( ! $parse ) {
if ( $return_headers ) {
return compact( 'response', 'headers' );
}
return $response;
}
$response = json_decode( $response );
if ( null === $response ) {
throw new Exception( 'Got unparseable response.' );
}
$this->response_cache[ $cache_key ] = $response;
if ( $return_headers ) {
return compact( 'response', 'headers' );
}
return $response;
}
}