WebResourcesGateway::get()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
rs 10
ccs 0
cts 5
cp 0
crap 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\SatCatalogosPopulate\Origins;
6
7
use GuzzleHttp\Client as GuzzleClient;
8
use GuzzleHttp\Exception\GuzzleException;
9
use GuzzleHttp\Exception\RequestException;
10
use GuzzleHttp\RequestOptions;
11
use Psr\Http\Message\ResponseInterface;
12
use RuntimeException;
13
14
class WebResourcesGateway implements ResourcesGatewayInterface
15
{
16
    private readonly GuzzleClient $client;
17
18
    public function __construct(GuzzleClient $client = null)
19
    {
20
        $this->client = $client ?? new GuzzleClient();
0 ignored issues
show
Bug introduced by
The property client is declared read-only in PhpCfdi\SatCatalogosPopu...ins\WebResourcesGateway.
Loading history...
21
    }
22
23
    private function obtainResponse(string $method, string $url): ResponseInterface
24
    {
25
        try {
26
            $response = $this->client->request($method, $url, [
27
                RequestOptions::DEBUG => false, // set to true to debug download problems
28
            ]);
29
        } catch (RequestException $exception) {
30
            if (! $exception->hasResponse()) {
31
                throw new RuntimeException("Unable to perform HTTP $method $url", 0, $exception);
32
            }
33
            /** @var ResponseInterface $response */
34
            $response = $exception->getResponse();
35
        } catch (GuzzleException $exception) {
36
            throw new RuntimeException("Unable to perform HTTP $method $url", 0, $exception);
37
        }
38
        return $response;
39
    }
40
41
    private function createUrlResponseFromResponse(ResponseInterface $response, string $url): UrlResponse
42
    {
43
        return UrlResponse::createFromResponse($response, $url);
44
    }
45
46
    public function headers(string $url): UrlResponse
47
    {
48
        $response = $this->obtainResponse('HEAD', $url);
49
        return $this->createUrlResponseFromResponse($response, $url);
50
    }
51
52
    public function get(string $url, string $destination): UrlResponse
53
    {
54
        $response = $this->obtainResponse('GET', $url);
55
        if (200 === $response->getStatusCode() && ! empty($destination)) {
56
            file_put_contents($destination, $response->getBody());
57
        }
58
59
        return $this->createUrlResponseFromResponse($response, $url);
60
    }
61
}
62