Fix currency precision
This commit is contained in:
Pedro Silva 2023-08-09 12:03:09 +01:00
parent bb3b8553b9
commit 2b497182d3
No known key found for this signature in database
GPG key ID: E2EE20C0669D24B3
3 changed files with 20 additions and 5 deletions

View file

@ -824,9 +824,11 @@ return array(
return new OrderTransient( $cache, $purchase_unit_sanitizer );
},
'api.helper.purchase-unit-sanitizer' => static function( ContainerInterface $container ): PurchaseUnitSanitizer {
if ( $instance = PurchaseUnitSanitizer::get_instance() ) {
$instance = PurchaseUnitSanitizer::get_instance();
if ( $instance ) {
return $instance;
}
$settings = $container->get( 'wcgateway.settings' );
assert( $settings instanceof Settings );

View file

@ -33,4 +33,16 @@ class MoneyFormatter {
? (string) round( $value, 0 )
: number_format( $value, 2, '.', '' );
}
/**
* Returns the minimum amount a currency can be incremented or decremented.
*
* @param string $currency The 3-letter currency code.
* @return float
*/
public function minimum_increment( string $currency ): float {
return (float) in_array( $currency, $this->currencies_without_decimals, true )
? 1.00
: 0.01;
}
}

View file

@ -172,8 +172,8 @@ class PurchaseUnitSanitizer {
/**
* The sanitizes the purchase_unit array.
*
* @param array $purchase_unit The purchase_unit array that should be sanitized.
* @param bool $allow_ditch_items Whether to allow items to be ditched.
* @param array $purchase_unit The purchase_unit array that should be sanitized.
* @param bool $allow_ditch_items Whether to allow items to be ditched.
* @return array
*/
public function sanitize( array $purchase_unit, bool $allow_ditch_items = true ): array {
@ -199,8 +199,9 @@ class PurchaseUnitSanitizer {
// Do floors on item amounts so item_mismatch is a positive value.
foreach ( $this->purchase_unit['items'] as $index => $item ) {
// get a more intelligent adjustment mechanism
$this->purchase_unit['items'][ $index ]['unit_amount']['value'] = ( (float) $this->purchase_unit['items'][ $index ]['unit_amount']['value'] ) - 0.01;
// Get a more intelligent adjustment mechanism.
$increment = ( new MoneyFormatter() )->minimum_increment( $item['unit_amount']['currency_code'] );
$this->purchase_unit['items'][ $index ]['unit_amount']['value'] = ( (float) $item['unit_amount']['value'] ) - $increment;
}
}