Is there a way to stop Order checkout in Commerce 2.x? Is there a way to stop an Order checkout process in Commerce 2.x when a product is out of stock?

Requirement:


I have a product with quantity in stock available as zero
A user/customer logs in
Customer clicks Add to cart button
Product must not be added to cart since it is unavailable in stock


I have used getSubscribedEvents() with Commerce order event commerce_order.commerce_order_item.insert. But the following code just won't work. I suspect it has something to do with the order of execution of  Symfony events but really don't understand where am I missing out. My code :

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events['commerce_order.commerce_order_item.insert'] = ['stopOrderExecutionOnStockUnavailability', 100];

    return $events;
  }

  /*
    -----
    -----
    -----
    -----
    -----
  */

  /**
   *
   * @param \Drupal\commerce_order\Event\OrderItemEvent $order_item
   *   OrderItemEvent object.
   */
   public function stopOrderExecutionOnStockUnavailability(OrderItemEvent $order_item) {

    $ordered_quantity = $order_item-&gt;getOrderItem()-&gt;getQuantity();
    $purchased_entity = $order_item-&gt;getOrderItem()-&gt;getPurchasedEntity();
    $stock_entities = $purchased_entity-&gt;get('field_stock_management')-&gt;getValue();

    // Check for available quantity in stock - in total.
    $available_quantity = 0;
    foreach ($stock_entities as $stock_entity) {
      /*
        Get total available stock quantity here.
      */
    }

    if ($ordered_quantity &gt; $available_quantity) {
      $order_item-&gt;stopPropagation();
      drupal_set_message(t('Ordered quantity is not available in stock.'), 'error');
    }
  }
Use Commerce's AvailabilityManager service.

See https://www.drupal.org/node/2511266 and https://www.drupal.org/node/2710107 for more information.