/** * Add a Purchasable to Cart as a new CartLine. * * This method creates a new CartLine and set item quantity * correspondingly. * * If the Purchasable is already in the Cart, it just increments * item quantity by $quantity * * @param CartInterface $cart Cart * @param PurchasableInterface $purchasable Product or Variant to add * @param int $quantity Number of units to set or increase * * @return $this Self object */ public function addPurchasable(CartInterface $cart, PurchasableInterface $purchasable, $quantity) { /** * If quantity is not a number or is 0 or less, product is not added * into cart. */ if (!is_int($quantity) || $quantity <= 0) { return $this; } foreach ($cart->getCartLines() as $cartLine) { /** * @var CartLineInterface $cartLine */ if (get_class($cartLine->getPurchasable()) === get_class($purchasable) && $cartLine->getPurchasable()->getId() == $purchasable->getId()) { /** * Product already in the Cart, increase quantity. */ return $this->increaseCartLineQuantity($cartLine, $quantity); } } $cartLine = $this->cartLineFactory->create(); $cartLine->setPurchasable($purchasable)->setQuantity($quantity); $this->addLine($cart, $cartLine); return $this; }
/** * addProduct. * * @dataProvider dataAddProduct * @group cart */ public function testAddProduct($quantity, $productCreated, $quantityExpected) { $cartLine = new CartLine(); $this->cartLineFactory->expects($this->exactly(intval($productCreated)))->method('create')->will($this->returnValue($cartLine)); /** * @var ProductInterface $product */ $product = $this->getMock('Elcodi\\Component\\Product\\Entity\\Interfaces\\ProductInterface'); $cart = new Cart(); $cart->setCartLines(new ArrayCollection()); $this->cartManager->addPurchasable($cart, $product, $quantity); if ($productCreated) { $createdLine = $cart->getCartLines()->first(); $createdProduct = $createdLine->getProduct(); $this->assertCount(1, $cart->getCartLines()); $this->assertInstanceOf('Elcodi\\Component\\Cart\\Entity\\Interfaces\\CartLineInterface', $createdLine); $this->assertSame($createdProduct, $product); $this->assertEquals($createdLine->getQuantity(), $quantityExpected); } else { $this->assertCount(0, $cart->getCartLines()); } }