UpdateExchangeRates   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 3
eloc 17
c 2
b 1
f 0
dl 0
loc 30
ccs 0
cts 16
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 18 3
1
<?php
2
/**
3
 * Update Exchange Rates.
4
 *
5
 * @package App\Jobs
6
 *
7
 * @author    Nick Menke <[email protected]>
8
 * @copyright 2018-2020 Nick Menke
9
 *
10
 * @link https://github.com/nlmenke/vertebrae
11
 */
12
13
declare(strict_types=1);
14
15
namespace App\Jobs;
16
17
use App\Entities\Currency\Currency;
18
use App\Services\Api\Currency\OpenExchangeRatesApiService;
19
use Exception;
20
use Illuminate\Bus\Queueable;
21
use Illuminate\Contracts\Queue\ShouldQueue;
22
use Illuminate\Foundation\Bus\Dispatchable;
23
use Illuminate\Queue\InteractsWithQueue;
24
use Illuminate\Queue\SerializesModels;
25
use Log;
26
27
/**
28
 * The Update Exchange Rates job class.
29
 *
30
 * This class updates currency exchange rates using the Open Exchange Rates
31
 * API. It is set to run quarterly by default. To utilize this job, you will
32
 * need to create an OXR account, which has a free tier for up to 1000
33
 * requests/month:
34
 *  - https://openexchangerates.org/
35
 *
36
 * @since x.x.x introduced
37
 */
38
class UpdateExchangeRates implements ShouldQueue
39
{
40
    use Dispatchable;
41
    use InteractsWithQueue;
42
    use Queueable;
43
    use SerializesModels;
44
45
    /**
46
     * Execute the job.
47
     *
48
     * @return void
49
     */
50
    public function handle(): void
51
    {
52
        try {
53
            $exchangeRatesApiService = app(OpenExchangeRatesApiService::class);
54
55
            $currencies = Currency::all();
56
            $exchangeRates = $exchangeRatesApiService->get('latest.json', null, ['base' => config('currency.default')]);
57
58
            $currencies->each(function (Currency $currency) use ($exchangeRates): void {
59
                if (array_key_exists($currency->getIsoAlpha(), $exchangeRates['rates'])) {
60
                    $currency->setAttribute('exchange_rate', $exchangeRates['rates'][$currency->getIsoAlpha()]);
61
                    $currency->save();
62
                } else {
63
                    Log::warning('Exchange rate for ' . $currency->getName() . ' does not exist in the OXR database');
64
                }
65
            });
66
        } catch (Exception $e) {
67
            Log::error($e->getMessage());
68
        }
69
    }
70
}
71