Issues (662)

src/Provider/WebProvider.php (1 issue)

1
<?php
2
3
namespace ICanBoogie\CLDR\Provider;
4
5
use CurlHandle;
6
use ICanBoogie\CLDR\GitHub\UrlResolver;
7
use ICanBoogie\CLDR\Provider;
8
9
use function curl_exec;
10
use function curl_getinfo;
11
use function curl_init;
12
use function curl_setopt;
13
use function curl_setopt_array;
14
use function is_string;
15
use function json_decode;
16
17
use const CURLINFO_HTTP_CODE;
18
use const CURLOPT_FAILONERROR;
19
use const CURLOPT_RETURNTRANSFER;
20
use const CURLOPT_URL;
21
22
/**
23
 * Retrieves sections from the CLDR source using cURL.
24
 */
25
final class WebProvider implements Provider
26
{
27
    private CurlHandle $connection;
28
29
    public function __construct(
30
        private readonly UrlResolver $url_resolver = new UrlResolver()
31
    ) {
32
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37
    public function provide(string $path): array
38
    {
39
        $connection = $this->obtain_connection();
40
        $url = $this->url_resolver->resolve($path);
41
42
        curl_setopt($connection, CURLOPT_URL, $url);
43
44
        $rc = curl_exec($connection);
45
46
        $http_code = curl_getinfo($connection, CURLINFO_HTTP_CODE);
47
48
        if ($http_code != 200) {
49
            throw new ResourceNotFound("Unable to fetch '$path', 'GET $url' responds with $http_code");
50
        }
51
52
        assert(is_string($rc));
53
54
        return json_decode($rc, true);
55
    }
56
57
    /**
58
     * Returns a reusable cURL connection.
59
     */
60
    private function obtain_connection(): CurlHandle
61
    {
62
        return $this->connection ??= $this->create_connection();
63
    }
64
65
    private function create_connection(): CurlHandle
66
    {
67
        $connection = curl_init();
68
69
        curl_setopt_array($connection, [
70
71
            CURLOPT_FAILONERROR => true,
72
            CURLOPT_RETURNTRANSFER => true
73
74
        ]);
75
76
        return $connection;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $connection could return the type resource which is incompatible with the type-hinted return CurlHandle. Consider adding an additional type-check to rule them out.
Loading history...
77
    }
78
}
79