Last active
December 12, 2015 06:29
-
-
Save pjedrzejewski/4729711 to your computer and use it in GitHub Desktop.
Adding different item types to cart.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Bundle\AppBundle\Resolver; | |
use Doctrine\Common\Persistence\ObjectRepository; | |
use Sylius\Bundle\CartBundle\Model\CartItemInterface; | |
use Sylius\Bundle\CartBundle\Resolver\ItemResolverInterface; | |
use Sylius\Bundle\CartBundle\Resolver\ItemResolvingException; | |
use Symfony\Component\HttpFoundation\Request; | |
class CartItemResolver implements ItemResolverInterface | |
{ | |
private $productRepository; | |
private $packageRepository; | |
public function __construct(ObjectRepository $productRepository, ObjectRepository $packageRepository) | |
{ | |
$this->productRepository = $productRepository; | |
$this->packageRepository = $packageRepository; | |
} | |
public function resolve(CartItemInterface $item, Request $request) | |
{ | |
if (null !== $productId = $request->get('productId')) { | |
return $this->resolveProduct($productId, $item, $request); | |
} | |
if (null !== $packageId = $request->get('packageId')) { | |
return $this->resolvePackage($packageId, $item, $request); | |
} | |
throw new ItemResolvingException('Error occured while adding item to cart'); | |
} | |
private function resolveProduct($id, CartItemInterface $item, Request $request) | |
{ | |
if (!$product = $this->productRepository->find($id)) { | |
throw new ItemResolvingException('Requested product is not available'); | |
} | |
$item->setProduct($product); | |
$item->setUnitPrice($product->getRetailPrice()); | |
return $item; | |
} | |
private function resolvePackage($id, CartItemInterface $item, Request $request) | |
{ | |
if (!$package = $this->packageRepository->find($id)) { | |
throw new ItemResolvingException('Requested package is not available'); | |
} | |
$item->setPackage($package); | |
$item->setUnitPrice($package->getRetailPrice()); | |
return $item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment