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

CurrencyConverter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 5
c 1
b 0
f 1
lcom 1
cbo 2
dl 0
loc 52
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getRate() 0 10 2
A generateRates() 0 11 2
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