Fix older WC compatibility

This commit is contained in:
Alex P. 2025-08-27 17:17:26 +03:00
parent 5d5775e02b
commit 049b31b611
No known key found for this signature in database
GPG key ID: 68E4DCB139B18520
2 changed files with 38 additions and 2 deletions

View file

@ -11,6 +11,8 @@ namespace WooCommerce\PayPalCommerce\ApiClient\Factory;
use WC_Cart;
use WC_Order;
use WC_Order_Item_Product;
use WC_Product;
use WooCommerce\PayPalCommerce\ApiClient\Entity\ExperienceContext;
use WooCommerce\PayPalCommerce\ApiClient\Entity\PurchaseUnit;
@ -41,7 +43,7 @@ class ShippingPreferenceFactory {
}
$has_shipping = null !== $purchase_unit->shipping();
$needs_shipping = ( $wc_order && $wc_order->needs_shipping() ) || ( $cart && $cart->needs_shipping() );
$needs_shipping = ( $wc_order && $this->wc_order_needs_shipping( $wc_order ) ) || ( $cart && $cart->needs_shipping() );
$shipping_address_is_fixed = $needs_shipping && in_array( $context, array( 'checkout', 'pay-now' ), true );
if ( ! $needs_shipping ) {
@ -67,4 +69,26 @@ class ShippingPreferenceFactory {
return ExperienceContext::SHIPPING_PREFERENCE_GET_FROM_FILE;
}
protected function wc_order_needs_shipping( WC_Order $wc_order ): bool {
// WC 9.9.0+.
if ( method_exists( $wc_order, 'needs_shipping' ) ) {
return $wc_order->needs_shipping();
}
if ( ! wc_shipping_enabled() || wc_get_shipping_method_count( true ) === 0 ) {
return false;
}
foreach ( $wc_order->get_items() as $item ) {
if ( $item instanceof WC_Order_Item_Product ) {
$product = $item->get_product();
if ( $product instanceof WC_Product && $product->needs_shipping() ) {
return true;
}
}
}
return false;
}
}

View file

@ -6,10 +6,13 @@ namespace WooCommerce\PayPalCommerce\ApiClient\Factory;
use Mockery;
use WC_Cart;
use WC_Order;
use WC_Order_Item_Product;
use WC_Product;
use WooCommerce\PayPalCommerce\ApiClient\Entity\ExperienceContext;
use WooCommerce\PayPalCommerce\ApiClient\Entity\PurchaseUnit;
use WooCommerce\PayPalCommerce\ApiClient\Entity\Shipping;
use WooCommerce\PayPalCommerce\TestCase;
use function Brain\Monkey\Functions\when;
class ShippingPreferenceFactoryTest extends TestCase
{
@ -19,6 +22,9 @@ class ShippingPreferenceFactoryTest extends TestCase
{
parent::setUp();
when('wc_shipping_enabled')->justReturn(true);
when('wc_get_shipping_method_count')->justReturn(2);
$this->testee = new ShippingPreferenceFactory();
}
@ -128,8 +134,14 @@ class ShippingPreferenceFactoryTest extends TestCase
}
private function createWcOrder(bool $needsShipping): WC_Order {
$product = Mockery::mock(WC_Product::class);
$product->shouldReceive('needs_shipping')->andReturn($needsShipping);
$item = Mockery::mock(WC_Order_Item_Product::class);
$item->shouldReceive('get_product')->andReturn($product);
$wcOrder = Mockery::mock(WC_Order::class);
$wcOrder->shouldReceive('needs_shipping')->andReturn($needsShipping);
$wcOrder->shouldReceive('get_items')->andReturn([$item]);
return $wcOrder;
}
}