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
|
<?php
/**
* The bundled PHP client, taught to speak through the WordPress HTTP API.
*
* @package CepisWooCommerce
*/
declare(strict_types=1);
defined( 'ABSPATH' ) || exit;
/**
* A `Cepis\Transport` over {@see wp_remote_get()}.
*
* The library defaults to talking to curl directly, which is the wrong thing
* to do inside WordPress: a site's proxy configuration, its
* `http_request_args` filters, its request timeouts and everything a host adds
* on top of the HTTP API would all be bypassed. Routing through
* {@see wp_remote_get()} keeps this plugin a well-behaved guest.
*
* Exactly one request per call, no retrying — retries, backoff and
* `Retry-After` stay the client's job.
*/
final class Cepis_Woo_Transport implements Cepis\Transport {
/**
* Body of the response to the most recent completed request.
*
* The client turns a 404 into a {@see Cepis\CepNotFoundException} and drops
* the body with it, which is the right shape for a library: a CEP that does
* not exist is an error, not a payload. The API nonetheless puts something
* useful in that body — the municipality the number would have belonged to —
* and this is the only place in the plugin that still has it.
*
* Kept here rather than handed to the client so that nothing downstream can
* mistake it for an address. {@see Cepis_Woo_Lookup} reads it, keeps the few
* fields that name a municipality, and passes them on inside the 404.
*
* @var string
*/
private string $last_body = '';
/**
* The body of the last response, or an empty string when the last request
* never completed.
*/
public function last_body(): string {
return $this->last_body;
}
/**
* Perform a single GET.
*
* @param string $url Absolute URL, query string included.
* @param array<string, string> $headers Request headers as name => value.
* @param float $timeout Seconds to allow for this attempt.
*
* @throws Cepis\NetworkException The request never completed.
*/
public function get( string $url, array $headers, float $timeout ): Cepis\Response {
$this->last_body = '';
$response = wp_remote_get(
$url,
array(
'headers' => $headers,
'timeout' => $timeout,
'redirection' => 3,
'sslverify' => true,
)
);
if ( is_wp_error( $response ) ) {
throw new Cepis\NetworkException( esc_html( $response->get_error_message() ) );
}
$response_headers = wp_remote_retrieve_headers( $response );
$this->last_body = (string) wp_remote_retrieve_body( $response );
return new Cepis\Response(
(int) wp_remote_retrieve_response_code( $response ),
is_object( $response_headers ) ? $response_headers->getAll() : (array) $response_headers,
$this->last_body
);
}
}
|