DependencyManagement
4 years ago
ProductAttributesLookup
4 years ago
WCCom
5 years ago
AssignDefaultCategory.php
5 years ago
DownloadPermissionsAdjuster.php
5 years ago
RestApiUtil.php
4 years ago
RestockRefundedItemsAdjuster.php
4 years ago
RestockRefundedItemsAdjuster.php
78 lines
| 1 | <?php |
| 2 | /** |
| 3 | * RestockRefundedItemsAdjuster class file. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Internal; |
| 7 | |
| 8 | use Automattic\WooCommerce\Proxies\LegacyProxy; |
| 9 | |
| 10 | defined( 'ABSPATH' ) || exit; |
| 11 | |
| 12 | /** |
| 13 | * Class to adjust or initialize the restock refunded items. |
| 14 | */ |
| 15 | class RestockRefundedItemsAdjuster { |
| 16 | /** |
| 17 | * The order factory to use. |
| 18 | * |
| 19 | * @var WC_Order_Factory |
| 20 | */ |
| 21 | private $order_factory; |
| 22 | |
| 23 | /** |
| 24 | * Class initialization, to be executed when the class is resolved by the container. |
| 25 | * |
| 26 | * @internal |
| 27 | */ |
| 28 | final public function init() { |
| 29 | $this->order_factory = wc_get_container()->get( LegacyProxy::class )->get_instance_of( \WC_Order_Factory::class ); |
| 30 | add_action( 'woocommerce_before_save_order_items', array( $this, 'initialize_restock_refunded_items' ), 10, 2 ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Initializes the restock refunded items meta for order version less than 5.5. |
| 35 | * |
| 36 | * @see https://github.com/woocommerce/woocommerce/issues/29502 |
| 37 | * |
| 38 | * @param int $order_id Order ID. |
| 39 | * @param array $items Order items to save. |
| 40 | */ |
| 41 | public function initialize_restock_refunded_items( $order_id, $items ) { |
| 42 | $order = wc_get_order( $order_id ); |
| 43 | $order_version = $order->get_version(); |
| 44 | |
| 45 | if ( version_compare( $order_version, '5.5', '>=' ) ) { |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | // If there are no refund lines, then this migration isn't necessary because restock related meta's wouldn't be set. |
| 50 | if ( 0 === count( $order->get_refunds() ) ) { |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | if ( isset( $items['order_item_id'] ) ) { |
| 55 | foreach ( $items['order_item_id'] as $item_id ) { |
| 56 | $item = $this->order_factory::get_order_item( absint( $item_id ) ); |
| 57 | |
| 58 | if ( ! $item ) { |
| 59 | continue; |
| 60 | } |
| 61 | |
| 62 | if ( 'line_item' !== $item->get_type() ) { |
| 63 | continue; |
| 64 | } |
| 65 | |
| 66 | // There could be code paths in custom code which don't update version number but still update the items. |
| 67 | if ( '' !== $item->get_meta( '_restock_refunded_items', true ) ) { |
| 68 | continue; |
| 69 | } |
| 70 | |
| 71 | $refunded_item_quantity = abs( $order->get_qty_refunded_for_item( $item->get_id() ) ); |
| 72 | $item->add_meta_data( '_restock_refunded_items', $refunded_item_quantity, false ); |
| 73 | $item->save(); |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 |