Skip to content

Commit

Permalink
[Customer] Refactor customer assignment to command
Browse files Browse the repository at this point in the history
  • Loading branch information
lchrusciel committed Jul 24, 2019
1 parent 1e9470a commit f80d609
Showing 1 changed file with 25 additions and 29 deletions.
54 changes: 25 additions & 29 deletions src/EventListener/CartBlamerListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,42 @@

use Doctrine\Common\Persistence\ObjectManager;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Context\CartNotFoundException;
use Sylius\Component\Order\Processor\OrderProcessorInterface;
use Sylius\ShopApiPlugin\Command\Cart\AssignCustomerToCart;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\MessageBusInterface;
use Webmozart\Assert\Assert;

final class CartBlamerListener
{
/** @var ObjectManager */
private $cartManager;

/** @var CartContextInterface */
private $cartContext;

/** @var OrderRepositoryInterface */
private $cartRepository;

/** @var MessageBusInterface */
private $bus;

/** @var OrderProcessorInterface */
private $orderProcessor;

/** @var RequestStack */
private $requestStack;

public function __construct(
ObjectManager $cartManager,
CartContextInterface $cartContext,
OrderRepositoryInterface $cartRepository,
MessageBusInterface $bus,
OrderProcessorInterface $orderProcessor,
RequestStack $requestStack
) {
$this->cartManager = $cartManager;
$this->cartContext = $cartContext;
$this->cartRepository = $cartRepository;
$this->bus = $bus;
$this->orderProcessor = $orderProcessor;
$this->requestStack = $requestStack;
}

Expand All @@ -51,33 +56,24 @@ public function onJwtLogin(JWTCreatedEvent $interactiveLoginEvent): void
return;
}

$cart = $this->getCart($request->request->get('token'));
$token = $request->request->get('token');

$cart = $this->cartRepository->findOneBy(['tokenValue' => $token]);

if (null === $cart) {
return;
}

$cart->setCustomer($user->getCustomer());
$this->cartManager->persist($cart);
$this->cartManager->flush();
}

private function getCart(?string $token): ?OrderInterface
{
if (null !== $token) {
/** @var OrderInterface $cart */
$cart = $this->cartRepository->findOneBy(['tokenValue' => $token]);

return $cart;
}
$this->bus->dispatch(
new AssignCustomerToCart(
$token,
$user->getCustomer()->getEmail()
)
);

try {
/** @var OrderInterface $cart */
$cart = $this->cartContext->getCart();
$this->orderProcessor->process($cart);

return $cart;
} catch (CartNotFoundException $exception) {
return null;
}
$this->cartManager->persist($cart);
$this->cartManager->flush();
}
}

0 comments on commit f80d609

Please sign in to comment.