CbrRateBuilder::fromXml()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 22
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 4
1
<?php
2
3
namespace Movavi\Builder;
4
5
use Movavi\Entity\Rate;
6
use Movavi\Exception\NoneRateException;
7
8
/**
9
 * Class AverageRateBuilder
10
 *
11
 * Builder for the Movavi\Entity\Rate
12
 * Implementation of Builder pattern (GoF)
13
 *
14
 * @package Movavi\Builder
15
 */
16
class CbrRateBuilder
17
{
18
19
    /**
20
     * Returns an instance of Movavi\Entity\Rate,
21
     * by string in xml-format from cbr.ru
22
     *
23
     * @param string $currencyFrom
24
     * @param string $currencyTo
25
     * @param \DateTime $date
26
     * @param string $xmlString
27
     *
28
     * @return Rate
29
     *
30
     * @throws NoneRateException
31
     */
32
    public function fromXml(string $currencyFrom, string $currencyTo, \DateTime $date, string $xmlString): Rate
33
    {
34
        $xml = simplexml_load_string($xmlString);
35
        $json = json_encode($xml);
36
        $array = json_decode($json, TRUE);
37
38
        if (empty($array['Record'])) {
39
            throw new NoneRateException('Service cbr.ru has not send any rate data');
40
        }
41
42
        if (isset($array['Record']['Value'])) {
43
44
            $rate = $array['Record']['Value'];
45
        } else {
46
47
            $record = array_shift($array['Record']);
48
            $rate = $record['Value'];
49
        }
50
51
        $rate = floatval(str_replace(',', '.', $rate));
52
53
        return new Rate($currencyFrom, $currencyTo, $date, $rate);
54
    }
55
}
56