-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Exchange.php
117 lines (88 loc) · 2.37 KB
/
Exchange.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php declare(strict_types=1);
namespace h4kuna\Exchange;
use ArrayAccess;
use h4kuna\Exchange\Exceptions\UnknownCurrencyException;
use h4kuna\Exchange\RatingList\RatingListInterface;
use IteratorAggregate;
/**
* @since 2009-06-22 - version 0.5
* @implements IteratorAggregate<string, CurrencyInterface>
* @implements ArrayAccess<string, CurrencyInterface>
* properties become readonly
*/
class Exchange implements IteratorAggregate, ArrayAccess
{
private CurrencyInterface $from;
private CurrencyInterface $to;
/**
* @param RatingListInterface<CurrencyInterface> $ratingList
*/
public function __construct(
string|CurrencyInterface $from,
public RatingListInterface $ratingList,
string|CurrencyInterface|null $to = null,
)
{
$this->from = $from instanceof CurrencyInterface ? $from : $this->get($from);
$this->to = $to === null
? $this->from
: ($to instanceof CurrencyInterface ? $to : $this->get($to));
}
/**
* @throws UnknownCurrencyException
*/
public function get(string $code): CurrencyInterface
{
return $this->ratingList->getSafe($code);
}
/**
* Transfer number by exchange rate.
*/
public function change(float|int|null $price, ?string $from = null, ?string $to = null): float
{
if ($price == 0) { // intentionally 0, 0.0, null
return .0;
}
$from = $this->getFrom($from);
$to = $this->getTo($to);
if ($to !== $from) {
$price *= $from->getRate() / $to->getRate();
}
return (float) $price;
}
public function getFrom(?string $from = null): CurrencyInterface
{
return $from === null ? $this->from : $this->ratingList->get($from);
}
public function getTo(?string $to = null): CurrencyInterface
{
return $to === null ? $this->to : $this->ratingList->get($to);
}
public function isValid(): bool
{
return $this->ratingList->isValid();
}
/**
* @return RatingListInterface<CurrencyInterface>
*/
public function getIterator(): RatingListInterface
{
return $this->ratingList;
}
public function offsetExists(mixed $offset): bool
{
return $this->ratingList->offsetExists($offset);
}
public function offsetGet(mixed $offset): CurrencyInterface
{
return $this->get($offset);
}
public function offsetSet(mixed $offset, mixed $value): void
{
$this->ratingList->offsetSet($offset, $value);
}
public function offsetUnset(mixed $offset): void
{
$this->ratingList->offsetUnset($offset);
}
}