-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
ExchangeRate.php
executable file
·371 lines (315 loc) · 10.3 KB
/
ExchangeRate.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
namespace AshAllenDesign\LaravelExchangeRates\Classes;
use AshAllenDesign\LaravelExchangeRates\Exceptions\ExchangeRateException;
use AshAllenDesign\LaravelExchangeRates\Exceptions\InvalidCurrencyException;
use AshAllenDesign\LaravelExchangeRates\Exceptions\InvalidDateException;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Client;
class ExchangeRate
{
/**
* The object used for making requests to the currency
* conversion API.
*
* @var RequestBuilder
*/
private $requestBuilder;
/**
* The repository used for accessing the cache.
*
* @var CacheRepository
*/
private $cacheRepository;
/**
* Whether of not the exchange rate should be cached
* after being fetched from the API.
*
* @var bool
*/
private $shouldCache = true;
/**
* Whether or not the cache should be busted and a new
* value should be fetched from the API.
*
* @var bool
*/
private $shouldBustCache = false;
/**
* ExchangeRate constructor.
*
* @param RequestBuilder|null $requestBuilder
* @param CacheRepository|null $cacheRepository
*/
public function __construct(RequestBuilder $requestBuilder = null, CacheRepository $cacheRepository = null)
{
$this->requestBuilder = $requestBuilder ?? new RequestBuilder(new Client());
$this->cacheRepository = $cacheRepository ?? new CacheRepository();
}
/**
* Return an array of available currencies that
* can be used with this package.
*
* @param array $currencies
*
* @return array
*/
public function currencies(array $currencies = []): array
{
$cacheKey = 'currencies';
if ($cachedExchangeRate = $this->attemptToResolveFromCache($cacheKey)) {
return $cachedExchangeRate;
}
$response = $this->requestBuilder->makeRequest('/latest', []);
$currencies[] = $response['base'];
foreach ($response['rates'] as $currency => $rate) {
$currencies[] = $currency;
}
if ($this->shouldCache) {
$this->cacheRepository->storeInCache($cacheKey, $currencies);
}
return $currencies;
}
/**
* Return the exchange rate between the $from and $to
* parameters. If no $date parameter is passed, we
* use today's date instead. If $to is a string,
* the exchange rate will be returned as a
* string. If $to is an array, the rates
* will be returned within an array.
*
* @param string $from
* @param string|array $to
* @param Carbon|null $date
*
* @return string|array
* @throws InvalidDateException
*
* @throws InvalidCurrencyException
* @throws ExchangeRateException
*/
public function exchangeRate(string $from, $to, Carbon $date = null)
{
Validation::validateIsStringOrArray($to);
if ($date) {
Validation::validateDate($date);
}
Validation::validateCurrencyCode($from);
is_string($to) ? Validation::validateCurrencyCode($to) : Validation::validateCurrencyCodes($to);
if ($from === $to) {
return 1.0;
}
$cacheKey = $this->cacheRepository->buildCacheKey($from, $to, $date ?? now());
if ($cachedExchangeRate = $this->attemptToResolveFromCache($cacheKey)) {
return $cachedExchangeRate;
}
$symbols = is_string($to) ? $to : implode(',', $to);
$queryParams = ['base' => $from, 'symbols' => $symbols];
$url = $date
? '/'.$date->format('Y-m-d')
: '/latest';
$response = $this->requestBuilder->makeRequest($url, $queryParams)['rates'];
$exchangeRate = is_string($to) ? $response[$to] : $response;
if ($this->shouldCache) {
$this->cacheRepository->storeInCache($cacheKey, $exchangeRate);
}
return $exchangeRate;
}
/**
* Return the exchange rates between the given
* date range.
*
* @param string $from
* @param string|array $to
* @param Carbon $date
* @param Carbon $endDate
* @param array $conversions
*
* @return array
* @throws Exception
*/
public function exchangeRateBetweenDateRange(
string $from,
$to,
Carbon $date,
Carbon $endDate,
array $conversions = []
): array {
Validation::validateCurrencyCode($from);
Validation::validateStartAndEndDates($date, $endDate);
Validation::validateIsStringOrArray($to);
is_string($to) ? Validation::validateCurrencyCode($to) : Validation::validateCurrencyCodes($to);
$cacheKey = $this->cacheRepository->buildCacheKey($from, $to, $date, $endDate);
if ($cachedExchangeRate = $this->attemptToResolveFromCache($cacheKey)) {
return $cachedExchangeRate;
}
$conversions = $from === $to
? $this->exchangeRateDateRangeResultWithSameCurrency($date, $endDate, $conversions)
: $conversions = $this->makeRequestForExchangeRates($from, $to, $date, $endDate);
if ($this->shouldCache) {
$this->cacheRepository->storeInCache($cacheKey, $conversions);
}
return $conversions;
}
/**
* Make a request to the Exchange Rates API to get the
* exchange rates between a date range. If only one
* currency is being used, we flatten the array
* to remove currency symbol before returning
* it.
*
* @param string $from
* @param string|array $to
* @param Carbon $date
* @param Carbon $endDate
* @return array
*/
private function makeRequestForExchangeRates(string $from, $to, Carbon $date, Carbon $endDate): array
{
$symbols = is_string($to) ? $to : implode(',', $to);
$result = $this->requestBuilder->makeRequest('/history', [
'base' => $from,
'start_at' => $date->format('Y-m-d'),
'end_at' => $endDate->format('Y-m-d'),
'symbols' => $symbols,
]);
$conversions = $result['rates'];
if (is_string($to)) {
foreach ($conversions as $date => $rate) {
$conversions[$date] = $rate[$to];
}
}
ksort($conversions);
return $conversions;
}
/**
* Return the converted values between the $from and $to
* parameters. If no $date parameter is passed, we
* use today's date instead.
*
* @param int $value
* @param string $from
* @param string|array $to
* @param Carbon|null $date
*
* @return float|array
* @throws InvalidDateException
*
* @throws InvalidCurrencyException
* @throws ExchangeRateException
*/
public function convert(int $value, string $from, $to, Carbon $date = null)
{
if (is_string($to)) {
return (float) $this->exchangeRate($from, $to, $date) * $value;
}
$exchangeRates = $this->exchangeRate($from, $to, $date);
foreach ($exchangeRates as $currency => $exchangeRate) {
$exchangeRates[$currency] = (float) $exchangeRate * $value;
}
return $exchangeRates;
}
/**
* Return an array of the converted values between the
* given date range.
*
* @param int $value
* @param string $from
* @param string|array $to
* @param Carbon $date
* @param Carbon $endDate
* @param array $conversions
*
* @return array
* @throws Exception
*/
public function convertBetweenDateRange(
int $value,
string $from,
$to,
Carbon $date,
Carbon $endDate,
array $conversions = []
): array {
$exchangeRates = $this->exchangeRateBetweenDateRange($from, $to, $date, $endDate);
if (is_array($to)) {
foreach ($exchangeRates as $date => $exchangeRate) {
foreach ($exchangeRate as $currency => $rate) {
$conversions[$date][$currency] = (float) $rate * $value;
}
}
return $conversions;
}
foreach ($exchangeRates as $date => $exchangeRate) {
$conversions[$date] = (float) $exchangeRate * $value;
}
return $conversions;
}
/**
* If the 'from' and 'to' currencies are the same, we
* don't need to make a request to the API. Instead,
* we can build the response ourselves to improve
* the performance.
*
* @param Carbon $startDate
* @param Carbon $endDate
* @param array $conversions
* @return array
*/
private function exchangeRateDateRangeResultWithSameCurrency(
Carbon $startDate,
Carbon $endDate,
array $conversions = []
): array {
for ($date = clone $startDate; $date->lte($endDate); $date->addDay()) {
if ($date->isWeekday()) {
$conversions[$date->format('Y-m-d')] = 1.0;
}
}
return $conversions;
}
/**
* Determine whether if the exchange rate should be
* cached after it is fetched from the API.
*
* @param bool $shouldCache
* @return $this
*/
public function shouldCache(bool $shouldCache = true): self
{
$this->shouldCache = $shouldCache;
return $this;
}
/**
* Determine whether if the cached result (if it
* exists) should be deleted. This will force
* a new exchange rate to be fetched from
* the API.
*
* @param bool $bustCache
* @return $this
*/
public function shouldBustCache(bool $bustCache = true): self
{
$this->shouldBustCache = $bustCache;
return $this;
}
/**
* Attempt to fetch an item (more than likely an
* exchange rate) from the cache. If it exists,
* return it. If it has been specified, bust
* the cache.
*
* @param string $cacheKey
* @return mixed
*/
private function attemptToResolveFromCache(string $cacheKey)
{
if ($this->shouldBustCache) {
$this->cacheRepository->forget($cacheKey);
$this->shouldBustCache = false;
} elseif ($cachedValue = $this->cacheRepository->getFromCache($cacheKey)) {
return $cachedValue;
}
}
}