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