CurrencySwitcher.php
81 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\TestData\Addons\CurrencySwitcher; |
| 4 | |
| 5 | use Exception; |
| 6 | use Give\TestData\Framework\MetaRepository; |
| 7 | |
| 8 | class CurrencySwitcher |
| 9 | { |
| 10 | |
| 11 | /** |
| 12 | * @param $currency |
| 13 | * |
| 14 | * @return float |
| 15 | */ |
| 16 | public function getCurrencyExchangeRate($currency) |
| 17 | { |
| 18 | $rates = give_get_option('cs_exchange_rates', []); |
| 19 | |
| 20 | if (array_key_exists($currency, $rates)) { |
| 21 | return $rates[$currency]['exchange_rate']; |
| 22 | } |
| 23 | |
| 24 | return 0.0; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * @param int $donationID |
| 29 | * @param array $donation |
| 30 | */ |
| 31 | public function addDonationCurrencyMeta($donationID, $donation) |
| 32 | { |
| 33 | // Bail out if donation currency is equal to default currency |
| 34 | if ($donation['payment_currency'] === give_get_currency()) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | global $wpdb; |
| 39 | |
| 40 | // Start DB transaction |
| 41 | $wpdb->query('START TRANSACTION'); |
| 42 | |
| 43 | try { |
| 44 | $exchangeRate = $this->getCurrencyExchangeRate($donation['payment_currency']); |
| 45 | $baseAmount = round($donation['payment_total'] / $exchangeRate, 6); |
| 46 | |
| 47 | // Update donation meta |
| 48 | $metaRepository = new MetaRepository('give_donationmeta', 'donation_id'); |
| 49 | $metaRepository->persist( |
| 50 | $donationID, |
| 51 | [ |
| 52 | '_give_cs_base_currency' => give_get_currency(), |
| 53 | '_give_cs_exchange_rate' => $exchangeRate, |
| 54 | '_give_cs_enabled' => 'enabled', |
| 55 | '_give_cs_base_amount' => $baseAmount, |
| 56 | ] |
| 57 | ); |
| 58 | |
| 59 | $wpdb->query('COMMIT'); |
| 60 | } catch (Exception $e) { |
| 61 | $wpdb->query('ROLLBACK'); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * @param array $donation |
| 67 | * @param array $params |
| 68 | * |
| 69 | * @return array |
| 70 | */ |
| 71 | public function setDonationCurrency($donation, $params) |
| 72 | { |
| 73 | if (isset($params['donation_currency'])) { |
| 74 | $donation['payment_currency'] = $params['donation_currency']; |
| 75 | } |
| 76 | |
| 77 | return $donation; |
| 78 | } |
| 79 | |
| 80 | } |
| 81 |