CurrencyConverter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
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 3
    public function __construct($base = "USD")
23
    {
24 3
        $this->base = $base;
25 3
        $this->client = new Client();
26 3
    }
27
28
    /**
29
     * @param $symbol
30
     * @return mixed
31
     * @throws \Exception
32
     */
33 3
    public function getRate($symbol)
34
    {
35 3
        $this->generateRates();
36
37 3
        if (!array_key_exists($symbol, $this->rates)) {
38
            throw new \Exception(sprintf('Unsupported Country Code, %s', $symbol));
39
        }
40
41 3
        return (double)filter_var($this->rates[$symbol], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
42
    }
43
44
    /**
45
     *
46
     */
47 3
    private function generateRates()
48
    {
49 3
        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 3
    }
58
59
    /**
60
     * @return array
61
     */
62 3
    public function getRates()
63
    {
64
        return $this->rates;
65 3
    }
66
67
    /**
68
     * @param array $rates
69
     */
70 3
    public function setRates($rates)
71
    {
72 3
        $this->rates = $rates;
73 3
    }
74
}
75