Completed
Push — master ( b97e2d...cc53db )
by Florian
9s
created

Swap::quote()   B

↳ Parent: Swap

Complexity

Conditions 6
Paths 9

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 33
Code Lines 18

Importance

Changes 9
Bugs 3 Features 3
Metric Value
c 9
b 3
f 3
dl 0
loc 33
rs 8.439
cc 6
eloc 18
nc 9
nop 1
1
<?php
2
3
/*
4
 * This file is part of Swap.
5
 *
6
 * (c) Florian Voutzinos <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Swap;
13
14
use Psr\Cache\CacheItemPoolInterface;
15
use Swap\Model\CurrencyPair;
16
use Swap\Model\Rate;
17
18
/**
19
 * An implementation of Swap.
20
 *
21
 * @author Florian Voutzinos <[email protected]>
22
 */
23
class Swap implements SwapInterface
24
{
25
    private $provider;
26
    private $cacheItemPool;
27
    private $cacheTtl;
28
29
    public function __construct(ProviderInterface $provider, CacheItemPoolInterface $cacheItemPool = null, $cacheTtl = 0)
30
    {
31
        $this->provider = $provider;
32
        $this->cacheItemPool = $cacheItemPool;
33
        $this->cacheTtl = $cacheTtl;
34
    }
35
36
    /**
37
     * [email protected]}
38
     */
39
    public function quote($currencyPair)
40
    {
41
        if (is_string($currencyPair)) {
42
            $currencyPair = CurrencyPair::createFromString($currencyPair);
43
        } elseif (!$currencyPair instanceof CurrencyPair) {
44
            throw new \InvalidArgumentException(
45
                'The currency pair must be either a string or an instance of CurrencyPair'
46
            );
47
        }
48
49
        if ($currencyPair->isIdentical()) {
50
            return new Rate(1);
51
        }
52
53
        if (null === $this->cacheItemPool) {
54
            return $this->provider->fetchRate($currencyPair);
55
        }
56
57
        $item = $this->cacheItemPool->getItem($currencyPair->toHash());
58
59
        if ($item->isHit()) {
60
            return $item->get();
61
        }
62
63
        $rate = $this->provider->fetchRate($currencyPair);
64
65
        $item->set($rate);
66
        $item->expiresAfter($this->cacheTtl);
67
68
        $this->cacheItemPool->save($item);
69
70
        return $rate;
71
    }
72
}
73