1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @package: marx/php-self-updater |
4
|
|
|
* |
5
|
|
|
* @author: msiebeneicher |
6
|
|
|
* @since: 2015-12-27 |
7
|
|
|
* |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace PSU\HttpClient\Adapter; |
11
|
|
|
|
12
|
|
|
use GuzzleHttp\ClientInterface; |
13
|
|
|
use PSU\Exception\HttpClientException; |
14
|
|
|
use PSU\HttpClient\HttpClientInterface; |
15
|
|
|
|
16
|
|
|
class GuzzlApapter implements HttpClientInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var ClientInterface |
20
|
|
|
*/ |
21
|
|
|
private $guzzlClient; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param ClientInterface $guzzlClient |
25
|
|
|
*/ |
26
|
3 |
|
public function __construct( |
27
|
|
|
ClientInterface $guzzlClient |
28
|
|
|
) |
29
|
|
|
{ |
30
|
3 |
|
$this->guzzlClient = $guzzlClient; |
31
|
3 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param $url |
35
|
|
|
* @return array |
36
|
|
|
* @throws HttpClientException |
37
|
|
|
*/ |
38
|
2 |
|
public function getJsonResponse($url) |
39
|
|
|
{ |
40
|
2 |
|
$response = $this->guzzlClient->get($url); |
41
|
2 |
|
if (200 == $response->getStatusCode()) |
42
|
2 |
|
{ |
43
|
1 |
|
return $response->json(); |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
throw new HttpClientException( |
47
|
1 |
|
sprintf( |
48
|
1 |
|
'Unable to get json result from "%s"', |
49
|
|
|
$url |
50
|
1 |
|
) |
51
|
1 |
|
); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param $url |
56
|
|
|
* @return string |
57
|
|
|
* @throws HttpClientException |
58
|
|
|
*/ |
59
|
|
|
public function download($url) |
60
|
|
|
{ |
61
|
|
|
$response = $this->guzzlClient->get($url); |
62
|
|
|
|
63
|
|
|
if (200 == $response->getStatusCode()) |
64
|
|
|
{ |
65
|
|
|
$body = $response->getBody(); |
66
|
|
|
return $this->saveBodyAsFile($body); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
throw new HttpClientException( |
70
|
|
|
sprintf( |
71
|
|
|
'Unable to get download from "%s"', |
72
|
|
|
$url |
73
|
|
|
) |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param $body |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
|
|
private function saveBodyAsFile($body) |
82
|
|
|
{ |
83
|
|
|
$tmpDir = sys_get_temp_dir(); |
84
|
|
|
$tmpFile = tempnam($tmpDir, 'psu_'); |
85
|
|
|
|
86
|
|
|
if (file_put_contents($tmpFile, $body) > 0) |
87
|
|
|
{ |
88
|
|
|
return $tmpFile; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
throw new \RuntimeException(sprintf('Unable to save file content to "%s"', $tmpFile)); |
92
|
|
|
} |
93
|
|
|
} |