Completed
Push — master ( 9fe4d8...b60226 )
by Restu
21:43 queued 06:38
created

CurrencyConverter::generateRates()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
namespace AaRestu\CurrencyConverter;
4
5
use GuzzleHttp\Client;
6
7
class CurrencyConverter
8
{
9
10
    private $url_api = "http://api.fixer.io/latest";
11
12
    private $base;
13
14
    private $rates = array();
15
16
    private $client;
17
18
    /**
19
     * CurrencyConverter constructor.
20
     * @param string $base
21
     */
22
    public function __construct($base = "USD")
23
    {
24
        $this->base = $base;
25
        $this->client = new Client();
26
    }
27
28
    /**
29
     * @param $symbol
30
     * @return mixed
31
     * @throws \Exception
32
     */
33
    public function getRate($symbol)
34
    {
35
        $this->generateRates();
36
37
        if (!array_key_exists($symbol, $this->rates)) {
38
            throw new \Exception(sprintf('Unsupported Country Code, %s', $symbol));
39
        }
40
41
        return (double)filter_var($this->rates[$symbol], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
42
    }
43
44
    /**
45
     *
46
     */
47
    private function generateRates()
48
    {
49
        if (empty($this->rates)) {
50
            $res = $this->client->request("GET", $this->url_api, [
51
                'query' => ['base' => $this->base]
52
            ]);
53
54
            $res_arr = \GuzzleHttp\json_decode($res->getBody(), true);
55
            $this->rates = $res_arr["rates"];
56
        }
57
    }
58
}
59