public function CartAddResource::post in Commerce Cart API 8
Add order items to the session's carts.
Parameters
array $data: The unserialized request body.
\Symfony\Component\HttpFoundation\Request $request: The request.
Return value
\Drupal\rest\ModifiedResourceResponse The resource response.
Throws
\Exception
File
- src/
Plugin/ rest/ resource/ CartAddResource.php, line 162
Class
- CartAddResource
- Creates order items for the session's carts.
Namespace
Drupal\commerce_cart_api\Plugin\rest\resourceCode
public function post(array $data, Request $request) {
$order_items = [];
// Do an initial validation of the payload before any processing.
foreach ($data as $key => $order_item_data) {
if (!isset($order_item_data['purchased_entity_type'])) {
throw new UnprocessableEntityHttpException(sprintf('You must specify a purchasable entity type for row: %s', $key));
}
if (!isset($order_item_data['purchased_entity_id'])) {
throw new UnprocessableEntityHttpException(sprintf('You must specify a purchasable entity ID for row: %s', $key));
}
if (!$this->entityTypeManager
->hasDefinition($order_item_data['purchased_entity_type'])) {
throw new UnprocessableEntityHttpException(sprintf('You must specify a valid purchasable entity type for row: %s', $key));
}
}
foreach ($data as $order_item_data) {
$storage = $this->entityTypeManager
->getStorage($order_item_data['purchased_entity_type']);
$purchased_entity = $storage
->load($order_item_data['purchased_entity_id']);
if (!$purchased_entity || !$purchased_entity instanceof PurchasableEntityInterface) {
continue;
}
$purchased_entity = $this->entityRepository
->getTranslationFromContext($purchased_entity);
$store = $this
->selectStore($purchased_entity);
$order_item = $this->orderItemStorage
->createFromPurchasableEntity($purchased_entity, [
'quantity' => !empty($order_item_data['quantity']) ? $order_item_data['quantity'] : 1,
]);
$context = new Context($this->currentUser, $store);
$order_item
->setUnitPrice($this->chainPriceResolver
->resolve($purchased_entity, $order_item
->getQuantity(), $context));
$order_type_id = $this->chainOrderTypeResolver
->resolve($order_item);
$cart = $this->cartProvider
->getCart($order_type_id, $store);
if (!$cart) {
$cart = $this->cartProvider
->createCart($order_type_id, $store);
}
if (!isset($order_item_data['combine'])) {
$order_item_data['combine'] = TRUE;
}
$order_items[] = $this->cartManager
->addOrderItem($cart, $order_item, $order_item_data['combine']);
}
$response = new ModifiedResourceResponse(array_values($order_items), 200);
return $response;
}