Sonata\ProductBundle\Controller\ProductController::getPriceStockForQuantityAction PHP Method

getPriceStockForQuantityAction() public method

Returns price for $productId in given quantity and stock information as JSON.
public getPriceStockForQuantityAction ( $productId ) : Symfony\Component\HttpFoundation\JsonResponse
$productId
return Symfony\Component\HttpFoundation\JsonResponse
    public function getPriceStockForQuantityAction($productId)
    {
        if (!$this->getRequest()->isXmlHttpRequest() || !($quantity = (int) $this->getRequest()->query->get('quantity'))) {
            throw new BadRequestHttpException('Request needs to be XHR and have a quantity parameter');
        }
        $product = $this->get('sonata.product.set.manager')->findOneBy(array('id' => $productId, 'enabled' => true));
        if (!$product) {
            throw new NotFoundHttpException(sprintf('Unable to find the product with id=%d', $productId));
        }
        $errors = array();
        /** @var \Sonata\Component\Product\Pool $productPool */
        $productPool = $this->get('sonata.product.pool');
        $provider = $productPool->getProvider($product);
        if ($provider->hasVariations($product)) {
            $errors['variations'] = 'This is a master product, it has no price';
        }
        $stock = $provider->getStockAvailable($product) ?: 0;
        if ($quantity > $stock) {
            $errors['stock'] = $this->get('translator')->trans('product_out_of_stock_quantity', array(), 'SonataProductBundle');
        }
        $currency = $this->get('sonata.basket')->getCurrency();
        $price = $provider->calculatePrice($product, $currency, true, $quantity);
        return new JsonResponse(array('stock' => $stock, 'price' => $price, 'price_text' => $this->get('sonata.intl.templating.helper.number')->formatCurrency($price, $currency), 'errors' => $errors));
    }