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(); |
|
|
|
|
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
|
|
|
|