1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SteffenBrand\CurrCurr\Mapper; |
4
|
|
|
|
5
|
|
|
use DateTime; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use SimpleXMLElement; |
8
|
|
|
use SteffenBrand\CurrCurr\Exception\ExchangeRatesMappingFailedException; |
9
|
|
|
use SteffenBrand\CurrCurr\Model\ExchangeRate; |
10
|
|
|
|
11
|
|
|
class ExchangeRatesMapper implements MapperInterface |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @param ResponseInterface $response |
16
|
|
|
* @return ExchangeRate[] |
17
|
|
|
*/ |
18
|
|
|
public function map(ResponseInterface $response): array |
19
|
|
|
{ |
20
|
|
|
$body = $response->getBody()->getContents(); |
21
|
|
|
$xml = $this->parseBody($body); |
22
|
|
|
$date = $this->parseDate($xml); |
23
|
|
|
$exchangeRates = $this->parseExchangeRates($xml, $date); |
24
|
|
|
|
25
|
|
|
return $exchangeRates; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $body |
30
|
|
|
* @return SimpleXMLElement |
31
|
|
|
*/ |
32
|
|
|
private function parseBody(string $body): SimpleXMLElement |
33
|
|
|
{ |
34
|
|
|
if (empty($body) === false) { |
35
|
|
|
libxml_use_internal_errors(true); |
36
|
|
|
$xml = simplexml_load_string($body); |
37
|
|
|
$errors = libxml_get_errors(); |
38
|
|
|
if (empty($errors) === true) { |
39
|
|
|
return $xml; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
throw new ExchangeRatesMappingFailedException(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param SimpleXMLElement $xml |
48
|
|
|
* @return DateTime |
49
|
|
|
*/ |
50
|
|
|
private function parseDate(SimpleXMLElement $xml): DateTime |
51
|
|
|
{ |
52
|
|
|
$date = DateTime::createFromFormat('Y-m-d', $xml->Cube->Cube['time']); |
53
|
|
|
if (false !== $date) { |
54
|
|
|
$date->setTime(0, 0); |
55
|
|
|
return $date; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
throw new ExchangeRatesMappingFailedException(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param SimpleXMLElement $xml |
63
|
|
|
* @param DateTime $date |
64
|
|
|
* @return array |
65
|
|
|
*/ |
66
|
|
|
private function parseExchangeRates(SimpleXMLElement $xml, DateTime $date): array |
67
|
|
|
{ |
68
|
|
|
$exchangeRates = []; |
69
|
|
|
|
70
|
|
|
foreach ($xml->Cube->Cube->Cube as $item) { |
71
|
|
|
$currency = strval($item['currency']); |
72
|
|
|
$rate = floatval($item['rate']); |
73
|
|
|
$exchangeRates[$currency] = new ExchangeRate( |
74
|
|
|
$currency, |
75
|
|
|
$rate, |
76
|
|
|
$date |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $exchangeRates; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
} |