You are here

public function CartUpdateItemsResource::patch in Commerce Cart API 8

PATCH to update order items.

Parameters

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

array $unserialized: The request body.

Return value

\Drupal\rest\ModifiedResourceResponse The response.

Throws

\Drupal\Core\Entity\EntityStorageException

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

File

src/Plugin/rest/resource/CartUpdateItemsResource.php, line 102

Class

CartUpdateItemsResource
Provides a cart collection resource for current session.

Namespace

Drupal\commerce_cart_api\Plugin\rest\resource

Code

public function patch(OrderInterface $commerce_order, array $unserialized) {
  $order_item_storage = $this->entityTypeManager
    ->getStorage('commerce_order_item');

  // Go through the request and validate the payload.
  $order_items = [];
  foreach ($unserialized as $order_item_id => $data) {
    $order_item = $order_item_storage
      ->load($order_item_id);
    if (!$order_item instanceof OrderItemInterface) {
      throw new UnprocessableEntityHttpException(sprintf('Unable to find order item %s', $order_item_id));
    }
    if (!$commerce_order
      ->hasItem($order_item)) {
      throw new UnprocessableEntityHttpException('Invalid order item');
    }
    if (count($data) > 1 || empty($data['quantity'])) {
      throw new UnprocessableEntityHttpException('You only have access to update the quantity');
    }
    if ($data['quantity'] < 1) {
      throw new UnprocessableEntityHttpException('Quantity must be positive value');
    }
    $order_item
      ->setQuantity($data['quantity']);
    $violations = $order_item
      ->validate();
    if (count($violations) > 0) {
      throw new UnprocessableEntityHttpException('You have provided an invalid quantity value');
    }
    $order_items[] = $order_item;
  }

  // We made it without errors, save the order items.
  foreach ($order_items as $order_item) {
    $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);
}