1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Orkhanahmadov\Currencylayer; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as Guzzle; |
6
|
|
|
|
7
|
|
|
class CurrencylayerClient implements Client |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var Guzzle |
11
|
|
|
*/ |
12
|
|
|
private $client; |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
private $accessKey; |
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
private $source; |
21
|
|
|
/** |
22
|
|
|
* @var string |
23
|
|
|
*/ |
24
|
|
|
private $currencies; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* CurrencylayerClient constructor. |
28
|
|
|
* |
29
|
|
|
* @param string $accessKey |
30
|
|
|
* @param bool $useHttps |
31
|
|
|
*/ |
32
|
|
|
public function __construct(string $accessKey, bool $useHttps = false) |
33
|
|
|
{ |
34
|
|
|
$this->client = new Guzzle([ |
35
|
|
|
'base_uri' => $useHttps ? 'https://apilayer.net/api/' : 'http://apilayer.net/api/' |
36
|
|
|
]); |
37
|
|
|
|
38
|
|
|
$this->accessKey = $accessKey; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $source |
43
|
|
|
* |
44
|
|
|
* @return $this |
45
|
|
|
*/ |
46
|
|
|
public function source(string $source): Client |
47
|
|
|
{ |
48
|
|
|
$this->source = $source; |
49
|
|
|
|
50
|
|
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param array<string> $currencies |
55
|
|
|
* |
56
|
|
|
* @return $this |
57
|
|
|
*/ |
58
|
|
|
public function currencies(array $currencies): Client |
59
|
|
|
{ |
60
|
|
|
$this->currencies = implode(',', $currencies); |
61
|
|
|
|
62
|
|
|
return $this; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @return array |
67
|
|
|
*/ |
68
|
|
|
public function live(): array |
69
|
|
|
{ |
70
|
|
|
return $this->request('live', [ |
71
|
|
|
'currencies' => $this->currencies, |
72
|
|
|
'source' => $this->source, |
73
|
|
|
]); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* |
78
|
|
|
* |
79
|
|
|
* @param string $endpoint |
80
|
|
|
* @param array $query |
81
|
|
|
* |
82
|
|
|
* @return array |
83
|
|
|
*/ |
84
|
|
|
private function request(string $endpoint, array $query): array |
85
|
|
|
{ |
86
|
|
|
$response = $this->client->get($endpoint, [ |
87
|
|
|
'query' => array_merge($query, ['access_key' => $this->accessKey]), |
88
|
|
|
]); |
89
|
|
|
|
90
|
|
|
$data = \GuzzleHttp\json_decode($response->getBody()->getContents(), true); |
91
|
|
|
|
92
|
|
|
if (array_key_exists('error', $data)) { |
93
|
|
|
throw new \InvalidArgumentException($data['error']['info']); |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
return $data; |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
/** |
100
|
|
|
* @param Guzzle $client |
101
|
|
|
*/ |
102
|
|
|
public function setClient(Guzzle $client): void |
103
|
|
|
{ |
104
|
|
|
$this->client = $client; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|