From 5b2710e0e452cff0bb927fd5e1e32aabad6ac458 Mon Sep 17 00:00:00 2001 From: mamazu Date: Wed, 28 Nov 2018 21:11:55 +0100 Subject: [PATCH] Changed the code to match the requirements --- src/Handler/CompleteOrderHandler.php | 34 +++++++++++++++++----------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/src/Handler/CompleteOrderHandler.php b/src/Handler/CompleteOrderHandler.php index 638d74301..4b70f466d 100644 --- a/src/Handler/CompleteOrderHandler.php +++ b/src/Handler/CompleteOrderHandler.php @@ -14,6 +14,7 @@ use Sylius\ShopApiPlugin\Command\CompleteOrder; use Sylius\ShopApiPlugin\Exception\WrongUserException; use Sylius\ShopApiPlugin\Provider\LoggedInUserProviderInterface; +use Symfony\Component\Security\Core\Exception\TokenNotFoundException; use Webmozart\Assert\Assert; final class CompleteOrderHandler @@ -67,25 +68,32 @@ public function handle(CompleteOrder $completeOrder) private function getCustomer(string $emailAddress): CustomerInterface { - /** @var CustomerInterface|null $customer */ - $customer = $this->customerRepository->findOneBy(['email' => $emailAddress]); + try { + $loggedInUser = $this->loggedInUserProvider->provide(); + + if($emailAddress !== ''){ + throw new \InvalidArgumentException('Can not have a logged in user and an email address'); + } - // If the customer does not exist then it's normal checkout - if ($customer === null) { /** @var CustomerInterface $customer */ - $customer = $this->customerFactory->createNew(); - $customer->setEmail($emailAddress); + $customer = $loggedInUser->getCustomer(); return $customer; - } + }catch (TokenNotFoundException $notLoggedIn){ - // If the customer does exist the user has to be logged in with this customer. Otherwise the user is not authorized to complete the checkout - $loggedInUser = $this->loggedInUserProvider->provide(); + /** @var CustomerInterface|null $customer */ + $customer = $this->customerRepository->findOneBy(['email' => $emailAddress]); - if ($loggedInUser->getCustomer() !== $customer) { - throw new WrongUserException(); - } + // If the customer does not exist then it's normal checkout + if ($customer === null) { + /** @var CustomerInterface $customer */ + $customer = $this->customerFactory->createNew(); + $customer->setEmail($emailAddress); - return $customer; + return $customer; + } else { + throw new WrongUserException('Email is already taken'); + } + } } }