Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ShipmentDocumentFactory.php
Go to the documentation of this file.
1 <?php
7 
14 use Magento\Sales\Model\Order\Shipment\TrackFactory;
20 
28 {
32  private $shipmentFactory;
33 
37  private $trackFactory;
38 
42  private $hydratorPool;
43 
47  private $extensionAttributesProcessor;
48 
57  public function __construct(
58  ShipmentFactory $shipmentFactory,
59  HydratorPool $hydratorPool,
60  TrackFactory $trackFactory,
61  ExtensionAttributesProcessor $extensionAttributesProcessor = null
62  ) {
63  $this->shipmentFactory = $shipmentFactory;
64  $this->trackFactory = $trackFactory;
65  $this->hydratorPool = $hydratorPool;
66  $this->extensionAttributesProcessor = $extensionAttributesProcessor ?: ObjectManager::getInstance()
67  ->get(ExtensionAttributesProcessor::class);
68  }
69 
83  public function create(
85  array $items = [],
86  array $tracks = [],
87  ShipmentCommentCreationInterface $comment = null,
88  $appendComment = false,
89  array $packages = [],
91  ) {
92  $shipmentItems = empty($items)
93  ? $this->getQuantitiesFromOrderItems($order->getItems())
94  : $this->getQuantitiesFromShipmentItems($items);
95 
97  $shipment = $this->shipmentFactory->create(
98  $order,
99  $shipmentItems
100  );
101 
102  if (null !== $arguments) {
103  $this->extensionAttributesProcessor->execute($shipment, $arguments);
104  }
105 
106  foreach ($tracks as $track) {
107  $hydrator = $this->hydratorPool->getHydrator(
108  \Magento\Sales\Api\Data\ShipmentTrackCreationInterface::class
109  );
110  $shipment->addTrack($this->trackFactory->create(['data' => $hydrator->extract($track)]));
111  }
112 
113  if ($comment) {
114  $shipment->addComment(
115  $comment->getComment(),
116  $appendComment,
117  $comment->getIsVisibleOnFront()
118  );
119 
120  if ($appendComment) {
121  $shipment->setCustomerNote($comment->getComment());
122  $shipment->setCustomerNoteNotify($appendComment);
123  }
124  }
125 
126  return $shipment;
127  }
128 
135  private function getQuantitiesFromOrderItems(array $items)
136  {
137  $shipmentItems = [];
138  foreach ($items as $item) {
139  if (!$item->getIsVirtual() && (!$item->getParentItem() || $item->isShipSeparately())) {
140  $shipmentItems[$item->getItemId()] = $item->getQtyOrdered();
141  }
142  }
143  return $shipmentItems;
144  }
145 
152  private function getQuantitiesFromShipmentItems(array $items)
153  {
154  $shipmentItems = [];
155  foreach ($items as $item) {
156  $shipmentItems[$item->getOrderItemId()] = $item->getQty();
157  }
158  return $shipmentItems;
159  }
160 }
__construct(ShipmentFactory $shipmentFactory, HydratorPool $hydratorPool, TrackFactory $trackFactory, ExtensionAttributesProcessor $extensionAttributesProcessor=null)
$track
Definition: details.phtml:12
$order
Definition: order.php:55
$arguments
foreach($order->getItems() as $orderItem) $shipment
$items