| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class WeightCalculator |
| 4 |
* |
| 5 |
* @package Packetery\Module\Weight |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace Packetery\Module; |
| 11 |
|
| 12 |
use Packetery\Core\CoreHelper; |
| 13 |
use Packetery\Module\Framework\WcAdapter; |
| 14 |
use Packetery\Module\Options\OptionsProvider; |
| 15 |
use WC_Order; |
| 16 |
use WC_Order_Item_Product; |
| 17 |
|
| 18 |
/** |
| 19 |
* Class WeightCalculator |
| 20 |
* |
| 21 |
* @package Packetery\Module\Order |
| 22 |
*/ |
| 23 |
class WeightCalculator { |
| 24 |
|
| 25 |
/** |
| 26 |
* @var OptionsProvider |
| 27 |
*/ |
| 28 |
private $optionsProvider; |
| 29 |
|
| 30 |
/** |
| 31 |
* @var WcAdapter |
| 32 |
*/ |
| 33 |
private $wcAdapter; |
| 34 |
|
| 35 |
public function __construct( |
| 36 |
OptionsProvider $optionsProvider, |
| 37 |
WcAdapter $wcAdapter |
| 38 |
) { |
| 39 |
$this->optionsProvider = $optionsProvider; |
| 40 |
$this->wcAdapter = $wcAdapter; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Calculates order weight ignoring user specified weight. |
| 45 |
* |
| 46 |
* @param WC_Order $order Order. |
| 47 |
* |
| 48 |
* @return float |
| 49 |
*/ |
| 50 |
public function calculateOrderWeight( WC_Order $order ): float { |
| 51 |
$weight = 0.0; |
| 52 |
foreach ( $order->get_items() as $item ) { |
| 53 |
$quantity = $item->get_quantity(); |
| 54 |
if ( $item instanceof WC_Order_Item_Product ) { |
| 55 |
$product = $item->get_product(); |
| 56 |
|
| 57 |
if ( is_object( $product ) && method_exists( $product, 'get_weight' ) ) { |
| 58 |
$productWeight = (float) $product->get_weight(); |
| 59 |
$weight += ( $productWeight * $quantity ); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
$weightKg = $this->wcAdapter->getWeight( $weight, 'kg' ); |
| 65 |
$weightKg += $this->optionsProvider->getPackagingWeight(); |
| 66 |
|
| 67 |
return CoreHelper::simplifyWeight( $weightKg ); |
| 68 |
} |
| 69 |
} |
| 70 |
|