You are here

public function CartCouponsResource::patch in Commerce Cart API 8

File

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

Class

CartCouponsResource
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) {

  // Add coupons.
  if (!isset($unserialized['coupon_code'])) {
    throw new BadRequestHttpException('Coupon code not provided.');
  }
  $coupon_storage = $this->entityTypeManager
    ->getStorage('commerce_promotion_coupon');
  assert($coupon_storage instanceof CouponStorageInterface);
  $coupon = $coupon_storage
    ->loadEnabledByCode($unserialized['coupon_code']);
  if (!$coupon instanceof CouponInterface) {
    throw new UnprocessableEntityHttpException(sprintf('%s is not a valid coupon code.', $unserialized['coupon_code']));
  }
  $commerce_order
    ->get('coupons')
    ->setValue([
    $coupon,
  ]);
  $this
    ->validate($commerce_order);
  try {
    $commerce_order
      ->setRefreshState(OrderInterface::REFRESH_ON_SAVE);
    $commerce_order
      ->save();
    return new ModifiedResourceResponse($commerce_order, 200);
  } catch (EntityStorageException $e) {
    throw new HttpException(500, 'Internal Server Error', $e);
  }
}