Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
OrderSave.php
Go to the documentation of this file.
1 <?php
9 
11 
12 class OrderSave
13 {
18 
23 
30  public function __construct(
31  \Magento\GiftMessage\Api\OrderRepositoryInterface $giftMessageOrderRepository,
32  \Magento\GiftMessage\Api\OrderItemRepositoryInterface $giftMessageOrderItemRepository
33  ) {
34  $this->giftMessageOrderRepository = $giftMessageOrderRepository;
35  $this->giftMessageOrderItemRepository = $giftMessageOrderItemRepository;
36  }
37 
47  public function afterSave(
48  \Magento\Sales\Api\OrderRepositoryInterface $subject,
49  \Magento\Sales\Api\Data\OrderInterface $resultOrder
50  ) {
52  $resultOrder = $this->saveOrderGiftMessage($resultOrder);
53  $resultOrder = $this->saveOrderItemGiftMessage($resultOrder);
54 
55  return $resultOrder;
56  }
57 
65  protected function saveOrderGiftMessage(\Magento\Sales\Api\Data\OrderInterface $order)
66  {
67  $extensionAttributes = $order->getExtensionAttributes();
68  if (null !== $extensionAttributes &&
69  null !== $extensionAttributes->getGiftMessage()
70  ) {
71  /* @var \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage */
72  $giftMessage = $extensionAttributes->getGiftMessage();
73  try {
74  $this->giftMessageOrderRepository->save($order->getEntityId(), $giftMessage);
75  } catch (\Exception $e) {
76  throw new CouldNotSaveException(
77  __('The gift message couldn\'t be added to the "%1" order.', $e->getMessage()),
78  $e
79  );
80  }
81  }
82  return $order;
83  }
84 
92  protected function saveOrderItemGiftMessage(\Magento\Sales\Api\Data\OrderInterface $order)
93  {
94  $items = $order->getItems();
95  if (null !== $items) {
97  foreach ($items as $orderItem) {
98  $extensionAttribute = $orderItem->getExtensionAttributes();
99  if (null !== $extensionAttribute &&
100  null !== $extensionAttribute->getGiftMessage()
101  ) {
102  /* @var \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage */
103  $giftMessage = $extensionAttribute->getGiftMessage();
104  try {
105  $this->giftMessageOrderItemRepository->save(
106  $order->getEntityId(),
107  $orderItem->getItemId(),
109  );
110  } catch (\Exception $e) {
111  throw new CouldNotSaveException(
112  __('The gift message couldn\'t be added to the "%1" order item.', $e->getMessage()),
113  $e
114  );
115  }
116  }
117  }
118  }
119  return $order;
120  }
121 }
$orderItem
Definition: order.php:30
$giftMessage
Definition: items.phtml:47
saveOrderGiftMessage(\Magento\Sales\Api\Data\OrderInterface $order)
Definition: OrderSave.php:65
$order
Definition: order.php:55
__()
Definition: __.php:13
$extensionAttributes
Definition: payment.php:22
__construct(\Magento\GiftMessage\Api\OrderRepositoryInterface $giftMessageOrderRepository, \Magento\GiftMessage\Api\OrderItemRepositoryInterface $giftMessageOrderItemRepository)
Definition: OrderSave.php:30
$items