-
Notifications
You must be signed in to change notification settings - Fork 4
/
WebProvider.php
78 lines (59 loc) · 1.7 KB
/
WebProvider.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
<?php
namespace ICanBoogie\CLDR\Provider;
use CurlHandle;
use ICanBoogie\CLDR\GitHub\UrlResolver;
use ICanBoogie\CLDR\Provider;
use function curl_exec;
use function curl_getinfo;
use function curl_init;
use function curl_setopt;
use function curl_setopt_array;
use function is_string;
use function json_decode;
use const CURLINFO_HTTP_CODE;
use const CURLOPT_FAILONERROR;
use const CURLOPT_RETURNTRANSFER;
use const CURLOPT_URL;
/**
* Retrieves sections from the CLDR source using cURL.
*/
final class WebProvider implements Provider
{
private CurlHandle $connection;
public function __construct(
private readonly UrlResolver $url_resolver = new UrlResolver()
) {
}
/**
* @inheritDoc
*/
public function provide(string $path): array
{
$connection = $this->obtain_connection();
$url = $this->url_resolver->resolve($path);
curl_setopt($connection, CURLOPT_URL, $url);
$rc = curl_exec($connection);
$http_code = curl_getinfo($connection, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
throw new ResourceNotFound("Unable to fetch '$path', 'GET $url' responds with $http_code");
}
assert(is_string($rc));
return json_decode($rc, true);
}
/**
* Returns a reusable cURL connection.
*/
private function obtain_connection(): CurlHandle
{
return $this->connection ??= $this->create_connection();
}
private function create_connection(): CurlHandle
{
$connection = curl_init();
curl_setopt_array($connection, [
CURLOPT_FAILONERROR => true,
CURLOPT_RETURNTRANSFER => true
]);
return $connection;
}
}