You are here

public function CartUpdateItemResource::patch in Commerce Cart API 8

PATCH to update order items.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $commerce_order: The order.

\Drupal\commerce_order\Entity\OrderItemInterface $commerce_order_item: The order item.

array $unserialized: The request body.

Return value

\Drupal\rest\ModifiedResourceResponse The response.

Throws

\Drupal\Core\Entity\EntityStorageException

File

src/Plugin/rest/resource/CartUpdateItemResource.php, line 103

Class

CartUpdateItemResource
Resource for updating the quantity of a cart's single order item.

Namespace

Drupal\commerce_cart_api\Plugin\rest\resource

Code

public function patch(OrderInterface $commerce_order, OrderItemInterface $commerce_order_item, array $unserialized) {
  if (count($unserialized) > 1 || empty($unserialized['quantity'])) {
    throw new UnprocessableEntityHttpException('You only have access to update the quantity');
  }
  if ($unserialized['quantity'] < 1) {
    throw new UnprocessableEntityHttpException('Quantity must be positive value');
  }
  $commerce_order_item
    ->setQuantity($unserialized['quantity']);
  $violations = $commerce_order_item
    ->validate();
  if (count($violations) > 0) {
    throw new UnprocessableEntityHttpException('You have provided an invalid quantity value');
  }
  $commerce_order_item
    ->save();
  $commerce_order
    ->setRefreshState(OrderInterface::REFRESH_ON_SAVE);
  $commerce_order
    ->save();

  // Return the updated entity in the response body.
  return new ModifiedResourceResponse($commerce_order, 200);
}