-
Notifications
You must be signed in to change notification settings - Fork 170
/
PaymentCurrencies.php
253 lines (214 loc) · 7.2 KB
/
PaymentCurrencies.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\commerce\services;
use Craft;
use craft\commerce\db\Table;
use craft\commerce\errors\CurrencyException;
use craft\commerce\models\PaymentCurrency;
use craft\commerce\Plugin;
use craft\commerce\records\PaymentCurrency as PaymentCurrencyRecord;
use craft\db\Query;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidConfigException;
/**
* Payment currency service.
*
* @property PaymentCurrency[]|array $allPaymentCurrencies
* @property PaymentCurrency|null $primaryPaymentCurrency the primary currency all prices are entered as
* @property string $primaryPaymentCurrencyIso the primary currencies ISO code as a string
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 2.0
*/
class PaymentCurrencies extends Component
{
// Properties
// =========================================================================
/**
* @var PaymentCurrency[]
*/
private $_allCurrenciesByIso;
/**
* @var PaymentCurrency[]
*/
private $_allCurrenciesById;
// Public Methods
// =========================================================================
/**
* Get payment currency by its ID.
*
* @param int $id
* @return PaymentCurrency|null
* @throws InvalidConfigException if currency has invalid iso code defined
*/
public function getPaymentCurrencyById($id)
{
if ($this->_allCurrenciesById === null) {
try {
$this->getAllPaymentCurrencies();
} catch (CurrencyException $exception) {
throw new InvalidConfigException($exception->getMessage());
}
}
return $this->_allCurrenciesById[$id] ?? null;
}
/**
* Get all payment currencies.
*
* @return PaymentCurrency[]
* @throws CurrencyException if currency does not exist with tat iso code
*/
public function getAllPaymentCurrencies(): array
{
if (null === $this->_allCurrenciesByIso) {
$rows = $this->_createPaymentCurrencyQuery()
->orderBy(['primary' => SORT_DESC, 'iso' => SORT_ASC])
->all();
$this->_allCurrenciesByIso = [];
foreach ($rows as $row) {
$paymentCurrency = new PaymentCurrency($row);
// TODO: Fix this with money/money package in 3.0
if (!$currency = Plugin::getInstance()->getCurrencies()->getCurrencyByIso($paymentCurrency->iso)) {
throw new CurrencyException(Plugin::t( 'No payment currency found with ISO code “{iso}”.', ['iso' => $paymentCurrency->iso]));
}
$paymentCurrency->setCurrency($currency);
$this->_memoizePaymentCurrency($paymentCurrency);
}
}
return $this->_allCurrenciesByIso;
}
/**
* Get a payment currency by its ISO code.
*
* @param string $iso
* @return PaymentCurrency
* @throws CurrencyException if currency does not exist with tat iso code
*/
public function getPaymentCurrencyByIso($iso): PaymentCurrency
{
if ($this->_allCurrenciesByIso === null) {
$this->getAllPaymentCurrencies();
}
if (isset($this->_allCurrenciesByIso[$iso])) {
return $this->_allCurrenciesByIso[$iso];
}
throw new CurrencyException(Plugin::t( 'No currency found with ISO code “{iso}”.', ['iso' => $iso]));
}
/**
* Return the primary currencies ISO code as a string.
*
* @return string
*/
public function getPrimaryPaymentCurrencyIso(): string
{
return $this->getPrimaryPaymentCurrency()->iso;
}
/**
* Returns the primary currency all prices are entered as.
*
* @return PaymentCurrency|null
*/
public function getPrimaryPaymentCurrency()
{
foreach ($this->getAllPaymentCurrencies() as $currency) {
if ($currency->primary) {
return $currency;
}
}
return null;
}
/**
* Convert an amount in site's primary currency to a different currecny by its ISO code.
*
* @param float $amount This is the unit of price in the primary store currency
* @param string $currency
* @return float
* @throws CurrencyException if currency not found by its ISO code
*/
public function convert(float $amount, string $currency): float
{
$destinationCurrency = $this->getPaymentCurrencyByIso($currency);
return $amount * $destinationCurrency->rate;
}
/**
* Save a payment currency.
*
* @param PaymentCurrency $model
* @param bool $runValidation should we validate this payment currency before saving.
* @return bool
* @throws Exception
*/
public function savePaymentCurrency(PaymentCurrency $model, bool $runValidation = true): bool
{
if ($model->id) {
$record = PaymentCurrencyRecord::findOne($model->id);
if (!$record) {
throw new Exception(Plugin::t( 'No currency exists with the ID “{id}”',
['id' => $model->id]));
}
} else {
$record = new PaymentCurrencyRecord();
}
if ($runValidation && !$model->validate()) {
Craft::info('Payment currency not saved due to validation error.', __METHOD__);
return false;
}
$record->iso = strtoupper($model->iso);
$record->primary = $model->primary;
// If this rate is primary, the rate must be 1 since it is now the rate all prices are enter in as.
$record->rate = $model->primary ? 1 : $model->rate;
$record->save(false);
// Now that we have a record ID, save it on the model
$model->id = $record->id;
if ($record->primary) {
PaymentCurrencyRecord::updateAll(['primary' => 0], ['not', ['id' => $record->id]]);
}
return true;
}
/**
* Delete a payment currency by its ID.
*
* @param $id
* @return bool
*/
public function deletePaymentCurrencyById($id): bool
{
$paymentCurrency = PaymentCurrencyRecord::findOne($id);
if ($paymentCurrency) {
return $paymentCurrency->delete();
}
return false;
}
// Private Methods
// =========================================================================
/**
* Memoize a payment currency
*
* @param PaymentCurrency $paymentCurrency
*/
private function _memoizePaymentCurrency(PaymentCurrency $paymentCurrency)
{
$this->_allCurrenciesByIso[$paymentCurrency->iso] = $paymentCurrency;
$this->_allCurrenciesById[$paymentCurrency->id] = $paymentCurrency;
}
/**
* Returns a Query object prepped for retrieving Emails
*
* @return Query
*/
private function _createPaymentCurrencyQuery(): Query
{
return (new Query())
->select([
'id',
'iso',
'primary',
'rate',
])
->from([Table::PAYMENTCURRENCIES]);
}
}