EuropeanCentralBankProvider::pickUrl()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 4
nc 6
nop 1
1
<?php
2
3
namespace BenTools\Currency\Provider;
4
5
use BenTools\Currency\Model\CurrencyInterface;
6
use BenTools\Currency\Model\ExchangeRateFactoryInterface;
7
use BenTools\Currency\Model\ExchangeRateInterface;
8
use BenTools\Currency\Model\ExchangeRateNotFoundException;
9
use BenTools\Currency\Model\NativeExchangeRateFactory;
10
use DateTime;
11
use DateTimeImmutable;
12
use DateTimeInterface;
13
use DateTimeZone;
14
use Http\Client\HttpClient;
15
use Http\Discovery\HttpClientDiscovery;
16
use Http\Discovery\MessageFactoryDiscovery;
17
use Http\Message\RequestFactory;
18
use Psr\SimpleCache\CacheInterface;
19
use SimpleXMLElement;
20
21
final class EuropeanCentralBankProvider implements ExchangeRateProviderInterface
22
{
23
24
    const LIVE_FEED_URL = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml';
25
    const NINETYDAYS_FEED_URL = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml';
26
    const FULL_FEED_URL = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml';
27
28
    /**
29
     * @var HttpClient|null
30
     */
31
    private $client;
32
33
    /**
34
     * @var RequestFactory|null
35
     */
36
    private $requestFactory;
37
38
    /**
39
     * @var ExchangeRateFactoryInterface|null
40
     */
41
    private $exchangeRateFactory;
42
43
    /**
44
     * EuropeanCentralBankProvider constructor.
45
     * @param HttpClient|null                   $client
46
     * @param RequestFactory|null               $requestFactory
47
     * @param ExchangeRateFactoryInterface|null $exchangeRateFactory
48
     * @throws \Http\Discovery\Exception\NotFoundException
49
     */
50
    public function __construct(
51
        HttpClient $client = null,
52
        RequestFactory $requestFactory = null,
53
        ExchangeRateFactoryInterface $exchangeRateFactory = null
54
    ) {
55
        $this->client = $client ?? HttpClientDiscovery::find();
56
        $this->requestFactory = $requestFactory ?? MessageFactoryDiscovery::find();
57
        $this->exchangeRateFactory = $exchangeRateFactory ?? new NativeExchangeRateFactory();
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function getExchangeRate(CurrencyInterface $sourceCurrency, CurrencyInterface $targetCurrency, DateTimeInterface $date = null): ExchangeRateInterface
64
    {
65
        if (null === $date) {
66
            $date = new DateTimeImmutable('now', new DateTimeZone('Europe/Paris'));
67
        }
68
69
        if ($date instanceof DateTime) {
70
            $date = DateTimeImmutable::createFromMutable($date)->setTimezone(new DateTimeZone('Europe/Paris'));
71
        }
72
73
        $dateString = $date->format('Y-m-d');
0 ignored issues
show
Bug introduced by
It seems like $date is not always an object, but can also be of type false. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
74
75
        if (!in_array('EUR', [$sourceCurrency->getCode(), $targetCurrency->getCode()])) {
76
            throw new ExchangeRateNotFoundException($sourceCurrency, $targetCurrency, "ECB only provide EUR-based currency conversions.");
77
        }
78
79
        // Same currencies
80
        if ($sourceCurrency->getCode() === $targetCurrency->getCode()) {
81
            return $this->exchangeRateFactory->create($sourceCurrency, $targetCurrency, 1);
82
        }
83
84
        // Invert currencies
85
        if ('EUR' === $targetCurrency->getCode()) { // ECB only provide EUR -> *
86
            $revertExchangeRate = $this->getExchangeRate($targetCurrency, $sourceCurrency, $date);
0 ignored issues
show
Security Bug introduced by
It seems like $date defined by \DateTimeImmutable::crea...meZone('Europe/Paris')) on line 70 can also be of type false; however, BenTools\Currency\Provid...ider::getExchangeRate() does only seem to accept null|object<DateTimeInterface>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
87
            return $this->exchangeRateFactory->create($sourceCurrency, $targetCurrency, 1 / $revertExchangeRate->getRatio());
88
        }
89
90
        $url = $this->pickUrl($date);
0 ignored issues
show
Security Bug introduced by
It seems like $date can also be of type false; however, BenTools\Currency\Provid...BankProvider::pickUrl() does only seem to accept object<DateTimeInterface>, did you maybe forget to handle an error condition?
Loading history...
91
        $response = $this->client->sendRequest($this->requestFactory->createRequest('GET', $url));
92
        $xml = new SimpleXMLElement($response->getBody());
93
94
        $rates = [];
95
        foreach ($xml->Cube->Cube as $cube) {
96
            foreach ($cube->Cube as $rate) {
97
                $currency = (string) $rate['currency'];
98
                $ratio = (float) (string) $rate['rate'];
99
                $rates[(string) $cube['time']][$currency] = $ratio;
100
            }
101
        }
102
103
        if (isset($rates[$dateString][$targetCurrency->getCode()])) {
104
            return $this->exchangeRateFactory->create($sourceCurrency, $targetCurrency, $rates[$dateString][$targetCurrency->getCode()]);
105
        }
106
107
        throw new ExchangeRateNotFoundException($sourceCurrency, $targetCurrency, sprintf('Unable to find exchange rate for %s to %s for the date `%s`.', $sourceCurrency->getCode(), $targetCurrency->getName(), $dateString));
108
    }
109
110
111
    /**
112
     * @param DateTimeInterface $date
113
     * @return string
114
     */
115
    private function pickUrl(DateTimeInterface $date): string
116
    {
117
        if ($date instanceof DateTime) {
118
            $date = DateTimeImmutable::createFromMutable($date);
119
        }
120
121
        $today = new DateTimeImmutable('today midnight', $date->getTimezone());
122
123
124
        switch (true) {
125
            case $date->format('Y-m-d') === $today->format('Y-m-d'):
126
                return static::LIVE_FEED_URL;
127
128
            case $date >= new DateTimeImmutable('-90 days', $date->getTimezone()):
129
                return static::NINETYDAYS_FEED_URL;
130
131
            default:
132
                return static::FULL_FEED_URL;
133
        }
134
    }
135
}
136