From 9f5015089eb0662e75a0951c48f2a03ba2f1bb84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Wed, 25 Oct 2017 06:15:20 -0700 Subject: [PATCH 01/34] [Address-book] Implement create address-book --- src/Command/CreateAddress.php | 162 ++++++++++++++++++ .../AddressBook/CreateAddressAction.php | 74 ++++++++ src/Handler/CreateAddressHandler.php | 125 ++++++++++++++ src/Request/CreateAddressRequest.php | 90 ++++++++++ src/Resources/config/routing.yml | 4 + src/Resources/config/routing/address_book.yml | 5 + .../config/services/actions/address_book.xml | 14 ++ src/Resources/config/services/controllers.xml | 1 + src/Resources/config/services/handlers.xml | 9 + .../validation/CreateAddressRequest.xml | 128 ++++++++++++++ 10 files changed, 612 insertions(+) create mode 100644 src/Command/CreateAddress.php create mode 100644 src/Controller/AddressBook/CreateAddressAction.php create mode 100644 src/Handler/CreateAddressHandler.php create mode 100644 src/Request/CreateAddressRequest.php create mode 100644 src/Resources/config/routing/address_book.yml create mode 100644 src/Resources/config/services/actions/address_book.xml create mode 100644 src/Resources/config/validation/CreateAddressRequest.xml diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php new file mode 100644 index 000000000..657c53600 --- /dev/null +++ b/src/Command/CreateAddress.php @@ -0,0 +1,162 @@ +firstName = $firstName; + $this->lastName = $lastName; + $this->company = $company; + $this->street = $street; + $this->countryCode = $countryCode; + $this->provinceName = $provinceName; + $this->city = $city; + $this->postcode = $postcode; + $this->phoneNumber = $phoneNumber; + } + + /** + * @return string + */ + public function firstName(): string + { + return $this->firstName; + } + + /** + * @return string + */ + public function lastName(): string + { + return $this->lastName; + } + + /** + * @return string|null + */ + public function company(): ?string + { + return $this->company; + } + + /** + * @return string + */ + public function street(): string + { + return $this->street; + } + + /** + * @return string + */ + public function countryCode(): string + { + return $this->countryCode; + } + + /** + * @return string|null + */ + public function provinceName(): ?string + { + return $this->provinceName; + } + + /** + * @return string + */ + public function city(): string + { + return $this->city; + } + + /** + * @return string + */ + public function postcode(): string + { + return $this->postcode; + } + + /** + * @return string|null + */ + public function phoneNumber(): ?string + { + return $this->phoneNumber; + } +} \ No newline at end of file diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php new file mode 100644 index 000000000..15c6ea413 --- /dev/null +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -0,0 +1,74 @@ +viewHandler = $viewHandler; + $this->bus = $bus; + $this->validator = $validator; + $this->validationErrorViewFactory = $validationErrorViewFactory; + } + + /** + * @param Request $request + * @return Response + */ + public function __invoke(Request $request): Response + { + $createAddressRequest = new CreateAddressRequest($request); + + $validationResults = $this->validator->validate($createAddressRequest); + + if (0 !== count($validationResults)) { + return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); + } + + $this->bus->handle($createAddressRequest->getCommand()); + + return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); + } +} \ No newline at end of file diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php new file mode 100644 index 000000000..5918a65ac --- /dev/null +++ b/src/Handler/CreateAddressHandler.php @@ -0,0 +1,125 @@ +addressRepository = $addressRepository; + $this->countryRepository = $countryRepository; + $this->provinceRepository = $provinceRepository; + $this->addressFactory = $addressFactory; + $this->tokenStorage = $tokenStorage; + } + + public function handle(CreateAddress $command): void + { + $user = $this->tokenStorage->getToken()->getUser(); + $customer = $user->getCustomer(); + + $this->assertShopUserExists($user); + $this->assertCountryExists($command->countryCode()); + + /** @var AddressInterface $address */ + $address = $this->addressFactory->createNew(); + $address->setFirstName($command->firstName()); + $address->setLastName($command->lastName()); + $address->setCompany($command->company()); + $address->setStreet($command->street()); + $address->setCountryCode($command->countryCode()); + $address->setCity($command->city()); + $address->setPostcode($command->postcode()); + $address->setPhoneNumber($command->phoneNumber()); + + if($command->provinceName()) { + $this->assertProvinceExists($command->provinceName()); + $address->setProvinceName($command->provinceName()); + $address->setProvinceCode($this->getProvinceCode($command->provinceName())); + } + + $customer->addAddress($address); + $this->addressRepository->add($address); + } + + /** + * @param string $countryCode + */ + private function assertCountryExists(string $countryCode): void + { + Assert::notNull($this->countryRepository->findOneBy(["code" => $countryCode]), 'Country does not exist.'); + } + + /** + * @param string $provinceName + */ + private function assertProvinceExists(string $provinceName): void + { + Assert::notNull($this->provinceRepository->findOneBy(["name" => $provinceName]), 'Province does not exist.'); + } + + /** + * @param string $provinceName + * @return mixed + */ + private function getProvinceCode(string $provinceName) + { + $province = $this->provinceRepository->findOneBy(["name" => $provinceName]); + return $province->getCode(); + } + + /** + * @param $user + */ + private function assertShopUserExists($user) + { + Assert::isInstanceOf($user, ShopUserInterface::class, "Logged in user does not exist"); + } +} \ No newline at end of file diff --git a/src/Request/CreateAddressRequest.php b/src/Request/CreateAddressRequest.php new file mode 100644 index 000000000..3f41f2745 --- /dev/null +++ b/src/Request/CreateAddressRequest.php @@ -0,0 +1,90 @@ +firstName = $request->request->get('firstName'); + $this->lastName = $request->request->get('lastName'); + $this->company = $request->request->get('company'); + $this->street = $request->request->get('street'); + $this->countryCode = $request->request->get('countryCode'); + $this->provinceName = $request->request->get('provinceName'); + $this->city = $request->request->get('city'); + $this->postcode = $request->request->get('postcode'); + $this->phoneNumber = $request->request->get('phoneNumber'); + } + + /** + * @return CreateAddress + */ + public function getCommand() + { + return new CreateAddress( + $this->firstName, + $this->lastName, + $this->company, + $this->street, + $this->countryCode, + $this->provinceName, + $this->city, + $this->postcode, + $this->phoneNumber + ); + } + +} \ No newline at end of file diff --git a/src/Resources/config/routing.yml b/src/Resources/config/routing.yml index 5971a7138..4185baf94 100644 --- a/src/Resources/config/routing.yml +++ b/src/Resources/config/routing.yml @@ -29,3 +29,7 @@ shop_api_customer: shop_api_product_list: resource: "@ShopApiPlugin/Resources/config/routing/productList.yml" prefix: /shop-api + +shop_api_address_book: + resource: "@ShopApiPlugin/Resources/config/routing/address_book.yml" + prefix: /shop-api diff --git a/src/Resources/config/routing/address_book.yml b/src/Resources/config/routing/address_book.yml new file mode 100644 index 000000000..b7ef87c76 --- /dev/null +++ b/src/Resources/config/routing/address_book.yml @@ -0,0 +1,5 @@ +sylius_shop_create_address_book_entry: + path: /address-book + methods: [POST] + defaults: + _controller: sylius.shop_api_plugin.controller.address_book.create_address_action diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml new file mode 100644 index 000000000..bd7512e80 --- /dev/null +++ b/src/Resources/config/services/actions/address_book.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + diff --git a/src/Resources/config/services/controllers.xml b/src/Resources/config/services/controllers.xml index ac6171892..4b549cd68 100644 --- a/src/Resources/config/services/controllers.xml +++ b/src/Resources/config/services/controllers.xml @@ -7,5 +7,6 @@ + diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index 8950f84b3..bf2734142 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -153,5 +153,14 @@ + + + + + + + + + diff --git a/src/Resources/config/validation/CreateAddressRequest.xml b/src/Resources/config/validation/CreateAddressRequest.xml new file mode 100644 index 000000000..a37dd3639 --- /dev/null +++ b/src/Resources/config/validation/CreateAddressRequest.xml @@ -0,0 +1,128 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 3892cac38fc1d8950a8ca79b0fc6353e46f315f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Wed, 25 Oct 2017 06:31:02 -0700 Subject: [PATCH 02/34] [Address-book] Removed unused valdiation messagess --- .../validation/CreateAddressRequest.xml | 62 ------------------- 1 file changed, 62 deletions(-) diff --git a/src/Resources/config/validation/CreateAddressRequest.xml b/src/Resources/config/validation/CreateAddressRequest.xml index a37dd3639..39e0fc3a9 100644 --- a/src/Resources/config/validation/CreateAddressRequest.xml +++ b/src/Resources/config/validation/CreateAddressRequest.xml @@ -3,125 +3,63 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 2481ea6edc0bf3bd6edd0902ee4c423e60a61d17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Wed, 25 Oct 2017 07:21:59 -0700 Subject: [PATCH 03/34] [Address-book] Changed province name to provinceCode --- src/Command/CreateAddress.php | 14 +++++++------- src/Handler/CreateAddressHandler.php | 25 +++++++++++++------------ src/Request/CreateAddressRequest.php | 6 +++--- 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index 657c53600..b43ee501f 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -34,7 +34,7 @@ final class CreateAddress /** * @var string */ - private $provinceName; + private $provinceCode; /** * @var string @@ -57,12 +57,12 @@ final class CreateAddress * @param $company * @param $street * @param $countryCode - * @param $provinceName + * @param $provinceCode * @param $city * @param $postcode * @param $phoneNumber */ - public function __construct($firstName, $lastName, $company, $street, $countryCode, $provinceName, $city, $postcode, $phoneNumber) + public function __construct($firstName, $lastName, $company, $street, $countryCode, $provinceCode, $city, $postcode, $phoneNumber) { Assert::allString([ $firstName, @@ -74,7 +74,7 @@ public function __construct($firstName, $lastName, $company, $street, $countryCo ]); Assert::nullOrString($company); - Assert::nullOrString($provinceName); + Assert::nullOrString($provinceCode); Assert::nullOrString($phoneNumber); $this->firstName = $firstName; @@ -82,7 +82,7 @@ public function __construct($firstName, $lastName, $company, $street, $countryCo $this->company = $company; $this->street = $street; $this->countryCode = $countryCode; - $this->provinceName = $provinceName; + $this->provinceCode = $provinceCode; $this->city = $city; $this->postcode = $postcode; $this->phoneNumber = $phoneNumber; @@ -131,9 +131,9 @@ public function countryCode(): string /** * @return string|null */ - public function provinceName(): ?string + public function provinceCode(): ?string { - return $this->provinceName; + return $this->provinceCode; } /** diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index 5918a65ac..41d998ee5 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -2,6 +2,7 @@ namespace Sylius\ShopApiPlugin\Handler; +use Sylius\Component\Addressing\Model\ProvinceInterface; use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Resource\Factory\FactoryInterface; @@ -79,10 +80,11 @@ public function handle(CreateAddress $command): void $address->setPostcode($command->postcode()); $address->setPhoneNumber($command->phoneNumber()); - if($command->provinceName()) { - $this->assertProvinceExists($command->provinceName()); - $address->setProvinceName($command->provinceName()); - $address->setProvinceCode($this->getProvinceCode($command->provinceName())); + if($command->provinceCode()) { + $province = $this->getProvince($command->provinceCode()); + $this->assertProvinceExists($province); + $address->setProvinceCode($province->getCode()); + $address->setProvinceName($province->getName()); } $customer->addAddress($address); @@ -98,21 +100,20 @@ private function assertCountryExists(string $countryCode): void } /** - * @param string $provinceName + * @param $province */ - private function assertProvinceExists(string $provinceName): void + private function assertProvinceExists($province): void { - Assert::notNull($this->provinceRepository->findOneBy(["name" => $provinceName]), 'Province does not exist.'); + Assert::notNull($province, 'Province does not exist.'); } /** - * @param string $provinceName - * @return mixed + * @param string $provinceCode + * @return ProvinceInterface|object */ - private function getProvinceCode(string $provinceName) + private function getProvince(string $provinceCode) { - $province = $this->provinceRepository->findOneBy(["name" => $provinceName]); - return $province->getCode(); + return $this->provinceRepository->findOneBy(["code" => $provinceCode]); } /** diff --git a/src/Request/CreateAddressRequest.php b/src/Request/CreateAddressRequest.php index 3f41f2745..026606e5b 100644 --- a/src/Request/CreateAddressRequest.php +++ b/src/Request/CreateAddressRequest.php @@ -35,7 +35,7 @@ class CreateAddressRequest /** * @var string */ - private $provinceName; + private $provinceCode; /** * @var string @@ -63,7 +63,7 @@ public function __construct(Request $request) $this->company = $request->request->get('company'); $this->street = $request->request->get('street'); $this->countryCode = $request->request->get('countryCode'); - $this->provinceName = $request->request->get('provinceName'); + $this->provinceCode = $request->request->get('provinceCode'); $this->city = $request->request->get('city'); $this->postcode = $request->request->get('postcode'); $this->phoneNumber = $request->request->get('phoneNumber'); @@ -80,7 +80,7 @@ public function getCommand() $this->company, $this->street, $this->countryCode, - $this->provinceName, + $this->provinceCode, $this->city, $this->postcode, $this->phoneNumber From d16ed25ad0a80b215fdb646b0831702773e0c450 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Thu, 26 Oct 2017 05:16:39 -0700 Subject: [PATCH 04/34] [Address-book] Add default address field to show action, and remove address endpoint --- src/Command/RemoveAddress.php | 28 +++++++ .../AddressBook/RemoveAddressAction.php | 78 +++++++++++++++++++ .../AddressBook/ShowAddressBookAction.php | 67 ++++++++++++++++ src/DependencyInjection/Configuration.php | 3 +- src/Factory/AddressBookViewFactory.php | 40 ++++++++++ .../AddressBookViewFactoryInterface.php | 14 ++++ src/Handler/RemoveAddressHandler.php | 55 +++++++++++++ src/Request/RemoveAddressRequest.php | 31 ++++++++ src/Resources/config/routing/address_book.yml | 12 +++ .../config/services/actions/address_book.xml | 18 ++++- src/Resources/config/services/factories.xml | 4 + src/Resources/config/services/handlers.xml | 5 ++ src/Resources/config/services/validators.xml | 6 ++ .../validation/RemoveAddressRequest.xml | 12 +++ src/Validator/AddressExistsValidator.php | 35 +++++++++ src/Validator/Constraints/AddressExists.php | 29 +++++++ src/View/AddressBookView.php | 53 +++++++++++++ 17 files changed, 488 insertions(+), 2 deletions(-) create mode 100644 src/Command/RemoveAddress.php create mode 100644 src/Controller/AddressBook/RemoveAddressAction.php create mode 100644 src/Controller/AddressBook/ShowAddressBookAction.php create mode 100644 src/Factory/AddressBookViewFactory.php create mode 100644 src/Factory/AddressBookViewFactoryInterface.php create mode 100644 src/Handler/RemoveAddressHandler.php create mode 100644 src/Request/RemoveAddressRequest.php create mode 100644 src/Resources/config/validation/RemoveAddressRequest.xml create mode 100644 src/Validator/AddressExistsValidator.php create mode 100644 src/Validator/Constraints/AddressExists.php create mode 100644 src/View/AddressBookView.php diff --git a/src/Command/RemoveAddress.php b/src/Command/RemoveAddress.php new file mode 100644 index 000000000..aeb3e941e --- /dev/null +++ b/src/Command/RemoveAddress.php @@ -0,0 +1,28 @@ +id = $id; + $this->user = $user; + } +} \ No newline at end of file diff --git a/src/Controller/AddressBook/RemoveAddressAction.php b/src/Controller/AddressBook/RemoveAddressAction.php new file mode 100644 index 000000000..cd1ed8f78 --- /dev/null +++ b/src/Controller/AddressBook/RemoveAddressAction.php @@ -0,0 +1,78 @@ +viewHandler = $viewHandler; + $this->validator = $validator; + $this->validationErrorViewFactory = $validationErrorViewFactory; + $this->bus = $bus; + $this->tokenStorage = $tokenStorage; + } + + public function __invoke(Request $request): Response + { + $removeAddressRequest = new RemoveAddressRequest($request, $this->tokenStorage->getToken()->getUser()); + + $validationResults = $this->validator->validate($removeAddressRequest); + + if (0 !== count($validationResults)) { + return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); + } + + $this->bus->handle($removeAddressRequest->getCommand()); + + return $this->viewHandler->handle(View::create("", Response::HTTP_NO_CONTENT)); + } +} \ No newline at end of file diff --git a/src/Controller/AddressBook/ShowAddressBookAction.php b/src/Controller/AddressBook/ShowAddressBookAction.php new file mode 100644 index 000000000..3921a95a9 --- /dev/null +++ b/src/Controller/AddressBook/ShowAddressBookAction.php @@ -0,0 +1,67 @@ +viewHandler = $viewHandler; + $this->tokenStorage = $tokenStorage; + $this->addressBookViewFactory = $addressBookViewFactory; + } + + public function __invoke(Request $request): Response + { + /** @var ShopUserInterface $user */ + $user = $this->tokenStorage->getToken()->getUser(); + + Assert::isInstanceOf($user, ShopUserInterface::class); + + /** @var Customer $customer */ + $customer = $user->getCustomer(); + $addresses = $customer->getAddresses(); + + $addressViews = []; + foreach ($addresses as $address) { + $addressViews[] = $this->addressBookViewFactory->create($address, $customer); + } + + return $this->viewHandler->handle(View::create($addressViews, Response::HTTP_OK)); + } +} \ No newline at end of file diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index dc506a5a7..429e36672 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -45,6 +45,7 @@ private function buildViewClassesNode(ArrayNodeDefinition $rootNode): void ->addDefaultsIfNotSet() ->children() ->scalarNode('address')->defaultValue(View\AddressView::class)->end() + ->scalarNode('address_book')->defaultValue(View\AddressBookView::class)->end() ->scalarNode('adjustment')->defaultValue(View\AdjustmentView::class)->end() ->scalarNode('cart_item')->defaultValue(View\ItemView::class)->end() ->scalarNode('cart_summary')->defaultValue(View\CartSummaryView::class)->end() @@ -63,7 +64,7 @@ private function buildViewClassesNode(ArrayNodeDefinition $rootNode): void ->scalarNode('product_variant')->defaultValue(View\ProductVariantView::class)->end() ->scalarNode('shipment')->defaultValue(View\ShipmentView::class)->end() ->scalarNode('shipping_method')->defaultValue(View\ShippingMethodView::class)->end() - ->scalarNode('taxon')->defaultValue(View\TaxonView::class)->end() + ->scalarNode('taxon')->defaultValue(View\TaxonView::class)->end()i ->scalarNode('taxon_details')->defaultValue(View\TaxonDetailsView::class)->end() ->scalarNode('totals')->defaultValue(View\TotalsView::class)->end() ->scalarNode('validation_error')->defaultValue(View\ValidationErrorView::class)->end() diff --git a/src/Factory/AddressBookViewFactory.php b/src/Factory/AddressBookViewFactory.php new file mode 100644 index 000000000..2e8bc7d30 --- /dev/null +++ b/src/Factory/AddressBookViewFactory.php @@ -0,0 +1,40 @@ +addressBookViewClass = $addressBookViewClass; + } + + /** + * {@inheritdoc} + */ + public function create(AddressInterface $address, CustomerInterface $customer): AddressBookView + { + /** @var AddressBookView $addressBookView */ + $addressBookView = new $this->addressBookViewClass(); + + $addressBookView->id = $address->getId(); + $addressBookView->firstName = $address->getFirstName(); + $addressBookView->lastName = $address->getLastName(); + $addressBookView->countryCode = $address->getCountryCode(); + $addressBookView->street = $address->getStreet(); + $addressBookView->city = $address->getCity(); + $addressBookView->postcode = $address->getPostcode(); + $addressBookView->provinceName = $address->getProvinceName(); + $addressBookView->default = $address === $customer->getDefaultAddress(); + + return $addressBookView; + } +} \ No newline at end of file diff --git a/src/Factory/AddressBookViewFactoryInterface.php b/src/Factory/AddressBookViewFactoryInterface.php new file mode 100644 index 000000000..d9cfc0b72 --- /dev/null +++ b/src/Factory/AddressBookViewFactoryInterface.php @@ -0,0 +1,14 @@ +addressRepository = $addressRepository; + $this->orderRepository = $orderRepository; + } + + public function handle(RemoveAddress $removeAddress) + { + /** @var AddressInterface $address */ + $address = $this->addressRepository->findOneBy(["id" => $removeAddress->id]); + + $this->assertCurrentUserIsOwner($address, $removeAddress->user); + $this->assertOrderWithAddressNotExists($address); + + $this->addressRepository->remove($address); + } + + private function assertOrderWithAddressNotExists($address) + { + /** @var OrderInterface $orderShippingAddress */ + $orderShippingAddress = $this->orderRepository->findBy(["billingAddress" => $address]); + /** @var OrderInterface $orderBillingAddress */ + $orderBillingAddress = $this->orderRepository->findBy(["shippingAddress" => $address]); + Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders'); + } + + private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) + { + Assert::eq($address->getCustomer()->getId(), $user->getId(), "User is not owner of this address"); + } +} \ No newline at end of file diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php new file mode 100644 index 000000000..18ec0325d --- /dev/null +++ b/src/Request/RemoveAddressRequest.php @@ -0,0 +1,31 @@ +id = $request->attributes->get('id'); + $this->user = $user; + } + + public function getCommand() + { + return new RemoveAddress($this->id, $this->user); + } +} \ No newline at end of file diff --git a/src/Resources/config/routing/address_book.yml b/src/Resources/config/routing/address_book.yml index b7ef87c76..b0905bb24 100644 --- a/src/Resources/config/routing/address_book.yml +++ b/src/Resources/config/routing/address_book.yml @@ -1,5 +1,17 @@ +sylius_shop_show_address_book: + path: /address-book + methods: [GET] + defaults: + _controller: sylius.shop_api_plugin.controller.address_book.show_address_book_action + sylius_shop_create_address_book_entry: path: /address-book methods: [POST] defaults: _controller: sylius.shop_api_plugin.controller.address_book.create_address_action + +sylius_shop_remove_address_book_entry: + path: /address-book/{id} + methods: [DELETE] + defaults: + _controller: sylius.shop_api_plugin.controller.address_book.remove_address_action diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index bd7512e80..097ae0adf 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -10,5 +10,21 @@ + + + + + + + + + + + + - + \ No newline at end of file diff --git a/src/Resources/config/services/factories.xml b/src/Resources/config/services/factories.xml index db4ffc6c6..40be97564 100644 --- a/src/Resources/config/services/factories.xml +++ b/src/Resources/config/services/factories.xml @@ -120,5 +120,9 @@ %sylius.shop_api.view.customer.class% + + + %sylius.shop_api.view.address_book.class% + diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index bf2734142..ebb58ba0c 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -162,5 +162,10 @@ + + + + + diff --git a/src/Resources/config/services/validators.xml b/src/Resources/config/services/validators.xml index be160e0e2..d1e9550a5 100644 --- a/src/Resources/config/services/validators.xml +++ b/src/Resources/config/services/validators.xml @@ -70,5 +70,11 @@ + + + + diff --git a/src/Resources/config/validation/RemoveAddressRequest.xml b/src/Resources/config/validation/RemoveAddressRequest.xml new file mode 100644 index 000000000..068455655 --- /dev/null +++ b/src/Resources/config/validation/RemoveAddressRequest.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/Validator/AddressExistsValidator.php b/src/Validator/AddressExistsValidator.php new file mode 100644 index 000000000..c533357ef --- /dev/null +++ b/src/Validator/AddressExistsValidator.php @@ -0,0 +1,35 @@ +addressRepository = $addressRepository; + } + + /** + * {@inheritdoc} + */ + public function validate($id, Constraint $constraint) + { + if (null === $this->addressRepository->findOneBy(['id' => $id])) { + $this->context->addViolation($constraint->message); + } + } +} \ No newline at end of file diff --git a/src/Validator/Constraints/AddressExists.php b/src/Validator/Constraints/AddressExists.php new file mode 100644 index 000000000..bbd45b19c --- /dev/null +++ b/src/Validator/Constraints/AddressExists.php @@ -0,0 +1,29 @@ + Date: Thu, 26 Oct 2017 05:17:36 -0700 Subject: [PATCH 05/34] Removed mistake --- src/DependencyInjection/Configuration.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 429e36672..5589ad686 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -64,7 +64,7 @@ private function buildViewClassesNode(ArrayNodeDefinition $rootNode): void ->scalarNode('product_variant')->defaultValue(View\ProductVariantView::class)->end() ->scalarNode('shipment')->defaultValue(View\ShipmentView::class)->end() ->scalarNode('shipping_method')->defaultValue(View\ShippingMethodView::class)->end() - ->scalarNode('taxon')->defaultValue(View\TaxonView::class)->end()i + ->scalarNode('taxon')->defaultValue(View\TaxonView::class)->end() ->scalarNode('taxon_details')->defaultValue(View\TaxonDetailsView::class)->end() ->scalarNode('totals')->defaultValue(View\TotalsView::class)->end() ->scalarNode('validation_error')->defaultValue(View\ValidationErrorView::class)->end() From e6efb471817b743136b8ff7de78266169cc73f7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 27 Oct 2017 10:27:13 +0200 Subject: [PATCH 06/34] [Address-book] Implement default address feature --- src/Command/SetDefaultAddress.php | 24 ++++++ .../AddressBook/CreateAddressAction.php | 2 +- .../AddressBook/SetDefaultAddress.php | 84 +++++++++++++++++++ .../AddressBook/UpdateAddressAction.php | 60 +++++++++++++ src/Handler/SetDefaultAddressHandler.php | 49 +++++++++++ src/Request/SetDefaultAddressRequest.php | 34 ++++++++ src/Resources/config/routing/address_book.yml | 13 +++ .../config/services/actions/address_book.xml | 19 +++++ src/Resources/config/services/handlers.xml | 5 ++ .../validation/SetDefaultAddressRequest.xml | 13 +++ src/Validator/AddressExistsValidator.php | 3 +- 11 files changed, 303 insertions(+), 3 deletions(-) create mode 100644 src/Command/SetDefaultAddress.php create mode 100644 src/Controller/AddressBook/SetDefaultAddress.php create mode 100644 src/Controller/AddressBook/UpdateAddressAction.php create mode 100644 src/Handler/SetDefaultAddressHandler.php create mode 100644 src/Request/SetDefaultAddressRequest.php create mode 100644 src/Resources/config/validation/SetDefaultAddressRequest.xml diff --git a/src/Command/SetDefaultAddress.php b/src/Command/SetDefaultAddress.php new file mode 100644 index 000000000..8ee56f368 --- /dev/null +++ b/src/Command/SetDefaultAddress.php @@ -0,0 +1,24 @@ +id = $id; + $this->user = $user; + } +} diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index 15c6ea413..49a03e897 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -71,4 +71,4 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } -} \ No newline at end of file +} diff --git a/src/Controller/AddressBook/SetDefaultAddress.php b/src/Controller/AddressBook/SetDefaultAddress.php new file mode 100644 index 000000000..70683c564 --- /dev/null +++ b/src/Controller/AddressBook/SetDefaultAddress.php @@ -0,0 +1,84 @@ +viewHandler = $viewHandler; + $this->bus = $bus; + $this->validator = $validator; + $this->validationErrorViewFactory = $validationErrorViewFactory; + $this->tokenStorage = $tokenStorage; + } + + /** + * @param Request $request + * @return Response + */ + public function __invoke(Request $request) + { + $setDefaultAddressRequest = new SetDefaultAddressRequest($request, $this->tokenStorage->getToken()->getUser()); + + $validationResults = $this->validator->validate($setDefaultAddressRequest); + + if (0 !== count($validationResults)) { + return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); + } + + $this->bus->handle($setDefaultAddressRequest->getCommand()); + + return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); + } +} + diff --git a/src/Controller/AddressBook/UpdateAddressAction.php b/src/Controller/AddressBook/UpdateAddressAction.php new file mode 100644 index 000000000..d0e76863a --- /dev/null +++ b/src/Controller/AddressBook/UpdateAddressAction.php @@ -0,0 +1,60 @@ +viewHandler = $viewHandler; + $this->tokenStorage = $tokenStorage; + $this->validator = $validator; + $this->serializer = $serializer; + } + + public function __invoke(Request $request): Response + { + return $this->viewHandler->handle(View::create([], Response::HTTP_OK)); + } +} \ No newline at end of file diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php new file mode 100644 index 000000000..5d60d7a50 --- /dev/null +++ b/src/Handler/SetDefaultAddressHandler.php @@ -0,0 +1,49 @@ +customerRepository = $customerRepository; + $this->addressRepository = $addressRepository; + } + + public function handle(SetDefaultAddress $setDefaultAddress): void + { + /** @var AddressInterface $address */ + $address = $this->addressRepository->find($setDefaultAddress->id); + /** @var CustomerInterface $customer */ + $customer = $setDefaultAddress->user->getCustomer(); + + $this->assertCurrentUserIsOwner($address, $setDefaultAddress->user); + + $customer->setDefaultAddress($address); + $this->customerRepository->add($customer); + } + + private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) + { + Assert::notNull($address->getCustomer(), 'Address is not associated with any user'); + Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address'); + } +} \ No newline at end of file diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php new file mode 100644 index 000000000..21fbc9845 --- /dev/null +++ b/src/Request/SetDefaultAddressRequest.php @@ -0,0 +1,34 @@ +id = $request->request->get('id'); + $this->user = $user; + } + + /** + * @return SetDefaultAddress + */ + public function getCommand() + { + return new SetDefaultAddress($this->id, $this->user); + } +} \ No newline at end of file diff --git a/src/Resources/config/routing/address_book.yml b/src/Resources/config/routing/address_book.yml index b0905bb24..818f30bc1 100644 --- a/src/Resources/config/routing/address_book.yml +++ b/src/Resources/config/routing/address_book.yml @@ -15,3 +15,16 @@ sylius_shop_remove_address_book_entry: methods: [DELETE] defaults: _controller: sylius.shop_api_plugin.controller.address_book.remove_address_action + +sylius_shop_set_default_address: + path: /address-book/default + methods: [PATCH] + defaults: + _controller: sylius.shop_api_plugin.controller.address_book.set_default_address_action + +sylius_shop_update_address_book_entry: + path: /address-book/{id} + methods: [PUT, PATCH] + defaults: + _controller: sylius.shop_api_plugin.controller.address_book.update_address_action + diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index 097ae0adf..d60b39602 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -26,5 +26,24 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index ebb58ba0c..986db8309 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -167,5 +167,10 @@ + + + + + diff --git a/src/Resources/config/validation/SetDefaultAddressRequest.xml b/src/Resources/config/validation/SetDefaultAddressRequest.xml new file mode 100644 index 000000000..a877897d0 --- /dev/null +++ b/src/Resources/config/validation/SetDefaultAddressRequest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/src/Validator/AddressExistsValidator.php b/src/Validator/AddressExistsValidator.php index c533357ef..fff8d6b46 100644 --- a/src/Validator/AddressExistsValidator.php +++ b/src/Validator/AddressExistsValidator.php @@ -2,7 +2,6 @@ namespace Sylius\ShopApiPlugin\Validator; - use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; @@ -32,4 +31,4 @@ public function validate($id, Constraint $constraint) $this->context->addViolation($constraint->message); } } -} \ No newline at end of file +} From 4f1a7d82d056c84ad331e8308caa9be3aec5f111 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 27 Oct 2017 10:37:16 +0200 Subject: [PATCH 07/34] [Address-book] Apply coding standard fixes --- src/Command/CreateAddress.php | 4 +++- src/Command/RemoveAddress.php | 4 +++- src/Command/SetDefaultAddress.php | 2 ++ .../AddressBook/CreateAddressAction.php | 13 ++++++++----- .../AddressBook/RemoveAddressAction.php | 9 +++++---- .../AddressBook/SetDefaultAddress.php | 8 +++++--- .../AddressBook/ShowAddressBookAction.php | 7 ++++--- .../AddressBook/UpdateAddressAction.php | 9 ++++----- src/Factory/AddressBookViewFactory.php | 5 +++-- src/Factory/AddressBookViewFactoryInterface.php | 4 ++-- src/Handler/CreateAddressHandler.php | 17 ++++++++++------- src/Handler/RemoveAddressHandler.php | 12 +++++++----- src/Handler/SetDefaultAddressHandler.php | 4 +++- src/Request/CreateAddressRequest.php | 6 ++++-- src/Request/RemoveAddressRequest.php | 4 +++- src/Request/SetDefaultAddressRequest.php | 4 +++- src/Validator/AddressExistsValidator.php | 3 +++ src/Validator/Constraints/AddressExists.php | 4 +++- src/View/AddressBookView.php | 2 +- 19 files changed, 76 insertions(+), 45 deletions(-) diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index b43ee501f..dd35a4b1e 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -1,5 +1,7 @@ phoneNumber; } -} \ No newline at end of file +} diff --git a/src/Command/RemoveAddress.php b/src/Command/RemoveAddress.php index aeb3e941e..71fe97530 100644 --- a/src/Command/RemoveAddress.php +++ b/src/Command/RemoveAddress.php @@ -1,5 +1,7 @@ id = $id; $this->user = $user; } -} \ No newline at end of file +} diff --git a/src/Command/SetDefaultAddress.php b/src/Command/SetDefaultAddress.php index 8ee56f368..5c17d78bc 100644 --- a/src/Command/SetDefaultAddress.php +++ b/src/Command/SetDefaultAddress.php @@ -1,5 +1,7 @@ viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; @@ -55,6 +57,7 @@ public function __construct( /** * @param Request $request + * * @return Response */ public function __invoke(Request $request): Response diff --git a/src/Controller/AddressBook/RemoveAddressAction.php b/src/Controller/AddressBook/RemoveAddressAction.php index cd1ed8f78..0ab928cf5 100644 --- a/src/Controller/AddressBook/RemoveAddressAction.php +++ b/src/Controller/AddressBook/RemoveAddressAction.php @@ -1,5 +1,7 @@ viewHandler = $viewHandler; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; @@ -73,6 +74,6 @@ public function __invoke(Request $request): Response $this->bus->handle($removeAddressRequest->getCommand()); - return $this->viewHandler->handle(View::create("", Response::HTTP_NO_CONTENT)); + return $this->viewHandler->handle(View::create('', Response::HTTP_NO_CONTENT)); } -} \ No newline at end of file +} diff --git a/src/Controller/AddressBook/SetDefaultAddress.php b/src/Controller/AddressBook/SetDefaultAddress.php index 70683c564..0c56e5dda 100644 --- a/src/Controller/AddressBook/SetDefaultAddress.php +++ b/src/Controller/AddressBook/SetDefaultAddress.php @@ -1,5 +1,7 @@ viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; @@ -64,6 +66,7 @@ public function __construct( /** * @param Request $request + * * @return Response */ public function __invoke(Request $request) @@ -81,4 +84,3 @@ public function __invoke(Request $request) return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } } - diff --git a/src/Controller/AddressBook/ShowAddressBookAction.php b/src/Controller/AddressBook/ShowAddressBookAction.php index 3921a95a9..01d9f105e 100644 --- a/src/Controller/AddressBook/ShowAddressBookAction.php +++ b/src/Controller/AddressBook/ShowAddressBookAction.php @@ -1,5 +1,7 @@ viewHandler = $viewHandler; $this->tokenStorage = $tokenStorage; $this->addressBookViewFactory = $addressBookViewFactory; @@ -64,4 +65,4 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create($addressViews, Response::HTTP_OK)); } -} \ No newline at end of file +} diff --git a/src/Controller/AddressBook/UpdateAddressAction.php b/src/Controller/AddressBook/UpdateAddressAction.php index d0e76863a..e79a2a944 100644 --- a/src/Controller/AddressBook/UpdateAddressAction.php +++ b/src/Controller/AddressBook/UpdateAddressAction.php @@ -1,12 +1,12 @@ viewHandler = $viewHandler; $this->tokenStorage = $tokenStorage; $this->validator = $validator; @@ -57,4 +56,4 @@ public function __invoke(Request $request): Response { return $this->viewHandler->handle(View::create([], Response::HTTP_OK)); } -} \ No newline at end of file +} diff --git a/src/Factory/AddressBookViewFactory.php b/src/Factory/AddressBookViewFactory.php index 2e8bc7d30..3c4aa0ee6 100644 --- a/src/Factory/AddressBookViewFactory.php +++ b/src/Factory/AddressBookViewFactory.php @@ -1,7 +1,8 @@ addressRepository = $addressRepository; $this->countryRepository = $countryRepository; $this->provinceRepository = $provinceRepository; @@ -80,7 +82,7 @@ public function handle(CreateAddress $command): void $address->setPostcode($command->postcode()); $address->setPhoneNumber($command->phoneNumber()); - if($command->provinceCode()) { + if ($command->provinceCode()) { $province = $this->getProvince($command->provinceCode()); $this->assertProvinceExists($province); $address->setProvinceCode($province->getCode()); @@ -96,7 +98,7 @@ public function handle(CreateAddress $command): void */ private function assertCountryExists(string $countryCode): void { - Assert::notNull($this->countryRepository->findOneBy(["code" => $countryCode]), 'Country does not exist.'); + Assert::notNull($this->countryRepository->findOneBy(['code' => $countryCode]), 'Country does not exist.'); } /** @@ -109,11 +111,12 @@ private function assertProvinceExists($province): void /** * @param string $provinceCode + * * @return ProvinceInterface|object */ private function getProvince(string $provinceCode) { - return $this->provinceRepository->findOneBy(["code" => $provinceCode]); + return $this->provinceRepository->findOneBy(['code' => $provinceCode]); } /** @@ -121,6 +124,6 @@ private function getProvince(string $provinceCode) */ private function assertShopUserExists($user) { - Assert::isInstanceOf($user, ShopUserInterface::class, "Logged in user does not exist"); + Assert::isInstanceOf($user, ShopUserInterface::class, 'Logged in user does not exist'); } -} \ No newline at end of file +} diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 3f24ce98c..89899e29f 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -1,5 +1,7 @@ addressRepository->findOneBy(["id" => $removeAddress->id]); + $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id]); $this->assertCurrentUserIsOwner($address, $removeAddress->user); $this->assertOrderWithAddressNotExists($address); @@ -42,14 +44,14 @@ public function handle(RemoveAddress $removeAddress) private function assertOrderWithAddressNotExists($address) { /** @var OrderInterface $orderShippingAddress */ - $orderShippingAddress = $this->orderRepository->findBy(["billingAddress" => $address]); + $orderShippingAddress = $this->orderRepository->findBy(['billingAddress' => $address]); /** @var OrderInterface $orderBillingAddress */ - $orderBillingAddress = $this->orderRepository->findBy(["shippingAddress" => $address]); + $orderBillingAddress = $this->orderRepository->findBy(['shippingAddress' => $address]); Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders'); } private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) { - Assert::eq($address->getCustomer()->getId(), $user->getId(), "User is not owner of this address"); + Assert::eq($address->getCustomer()->getId(), $user->getId(), 'User is not owner of this address'); } -} \ No newline at end of file +} diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index 5d60d7a50..71e848264 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -1,5 +1,7 @@ getCustomer(), 'Address is not associated with any user'); Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address'); } -} \ No newline at end of file +} diff --git a/src/Request/CreateAddressRequest.php b/src/Request/CreateAddressRequest.php index 026606e5b..88434251d 100644 --- a/src/Request/CreateAddressRequest.php +++ b/src/Request/CreateAddressRequest.php @@ -1,5 +1,7 @@ phoneNumber ); } - -} \ No newline at end of file +} diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php index 18ec0325d..c28c3abfb 100644 --- a/src/Request/RemoveAddressRequest.php +++ b/src/Request/RemoveAddressRequest.php @@ -1,5 +1,7 @@ id, $this->user); } -} \ No newline at end of file +} diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index 21fbc9845..81ee894c3 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -1,5 +1,7 @@ id, $this->user); } -} \ No newline at end of file +} diff --git a/src/Validator/AddressExistsValidator.php b/src/Validator/AddressExistsValidator.php index fff8d6b46..ddf77972a 100644 --- a/src/Validator/AddressExistsValidator.php +++ b/src/Validator/AddressExistsValidator.php @@ -1,5 +1,7 @@ Date: Fri, 27 Oct 2017 10:40:29 +0200 Subject: [PATCH 08/34] [Address-book] Add final keyword to classes --- src/Controller/AddressBook/RemoveAddressAction.php | 2 +- src/Controller/AddressBook/ShowAddressBookAction.php | 2 +- src/Controller/AddressBook/UpdateAddressAction.php | 2 +- src/Factory/AddressBookViewFactory.php | 2 +- src/Handler/RemoveAddressHandler.php | 2 +- src/Handler/SetDefaultAddressHandler.php | 2 +- src/Request/CreateAddressRequest.php | 2 +- src/Request/RemoveAddressRequest.php | 2 +- src/Request/SetDefaultAddressRequest.php | 2 +- src/Validator/AddressExistsValidator.php | 2 +- src/Validator/Constraints/AddressExists.php | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Controller/AddressBook/RemoveAddressAction.php b/src/Controller/AddressBook/RemoveAddressAction.php index 0ab928cf5..a8ebc0efe 100644 --- a/src/Controller/AddressBook/RemoveAddressAction.php +++ b/src/Controller/AddressBook/RemoveAddressAction.php @@ -14,7 +14,7 @@ use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; -class RemoveAddressAction +final class RemoveAddressAction { /** * @var ViewHandlerInterface diff --git a/src/Controller/AddressBook/ShowAddressBookAction.php b/src/Controller/AddressBook/ShowAddressBookAction.php index 01d9f105e..f0715b638 100644 --- a/src/Controller/AddressBook/ShowAddressBookAction.php +++ b/src/Controller/AddressBook/ShowAddressBookAction.php @@ -15,7 +15,7 @@ use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; -class ShowAddressBookAction +final class ShowAddressBookAction { /** * @var ViewHandlerInterface diff --git a/src/Controller/AddressBook/UpdateAddressAction.php b/src/Controller/AddressBook/UpdateAddressAction.php index e79a2a944..31b34fc34 100644 --- a/src/Controller/AddressBook/UpdateAddressAction.php +++ b/src/Controller/AddressBook/UpdateAddressAction.php @@ -12,7 +12,7 @@ use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; -class UpdateAddressAction +final class UpdateAddressAction { /** * @var ViewHandlerInterface diff --git a/src/Factory/AddressBookViewFactory.php b/src/Factory/AddressBookViewFactory.php index 3c4aa0ee6..adb729c81 100644 --- a/src/Factory/AddressBookViewFactory.php +++ b/src/Factory/AddressBookViewFactory.php @@ -8,7 +8,7 @@ use Sylius\Component\Core\Model\CustomerInterface; use Sylius\ShopApiPlugin\View\AddressBookView; -class AddressBookViewFactory implements AddressBookViewFactoryInterface +final class AddressBookViewFactory implements AddressBookViewFactoryInterface { /** @var string */ private $addressBookViewClass; diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 89899e29f..0bfce7d14 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -12,7 +12,7 @@ use Sylius\ShopApiPlugin\Command\RemoveAddress; use Webmozart\Assert\Assert; -class RemoveAddressHandler +final class RemoveAddressHandler { /** * @var AddressRepositoryInterface diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index 71e848264..5bbbf09cc 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -12,7 +12,7 @@ use Sylius\ShopApiPlugin\Command\SetDefaultAddress; use Webmozart\Assert\Assert; -class SetDefaultAddressHandler +final class SetDefaultAddressHandler { /** * @var CustomerRepositoryInterface diff --git a/src/Request/CreateAddressRequest.php b/src/Request/CreateAddressRequest.php index 88434251d..5b452b639 100644 --- a/src/Request/CreateAddressRequest.php +++ b/src/Request/CreateAddressRequest.php @@ -7,7 +7,7 @@ use Sylius\ShopApiPlugin\Command\CreateAddress; use Symfony\Component\HttpFoundation\Request; -class CreateAddressRequest +final class CreateAddressRequest { /** * @var string diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php index c28c3abfb..030709dcd 100644 --- a/src/Request/RemoveAddressRequest.php +++ b/src/Request/RemoveAddressRequest.php @@ -8,7 +8,7 @@ use Sylius\ShopApiPlugin\Command\RemoveAddress; use Symfony\Component\HttpFoundation\Request; -class RemoveAddressRequest +final class RemoveAddressRequest { /** * @var mixed diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index 81ee894c3..6a7cf1df9 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -8,7 +8,7 @@ use Sylius\ShopApiPlugin\Command\SetDefaultAddress; use Symfony\Component\HttpFoundation\Request; -class SetDefaultAddressRequest +final class SetDefaultAddressRequest { /** * @var mixed diff --git a/src/Validator/AddressExistsValidator.php b/src/Validator/AddressExistsValidator.php index ddf77972a..76e369f99 100644 --- a/src/Validator/AddressExistsValidator.php +++ b/src/Validator/AddressExistsValidator.php @@ -8,7 +8,7 @@ use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; -class AddressExistsValidator extends ConstraintValidator +final class AddressExistsValidator extends ConstraintValidator { /** * @var AddressRepositoryInterface diff --git a/src/Validator/Constraints/AddressExists.php b/src/Validator/Constraints/AddressExists.php index 6878ebbff..833e1e83d 100644 --- a/src/Validator/Constraints/AddressExists.php +++ b/src/Validator/Constraints/AddressExists.php @@ -6,7 +6,7 @@ use Symfony\Component\Validator\Constraint; -class AddressExists extends Constraint +final class AddressExists extends Constraint { /** * @var string From a158958c4e0791b71c98b9829a545e7fb9bfca66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 27 Oct 2017 10:52:20 +0200 Subject: [PATCH 09/34] [Address-book] Apply scrutinizer fixes and updated existing test --- src/Controller/AddressBook/ShowAddressBookAction.php | 2 +- src/Handler/CreateAddressHandler.php | 2 +- tests/DependencyInjection/ConfigurationTest.php | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Controller/AddressBook/ShowAddressBookAction.php b/src/Controller/AddressBook/ShowAddressBookAction.php index f0715b638..1fd809008 100644 --- a/src/Controller/AddressBook/ShowAddressBookAction.php +++ b/src/Controller/AddressBook/ShowAddressBookAction.php @@ -28,7 +28,7 @@ final class ShowAddressBookAction private $tokenStorage; /** - * @var AddressViewFactory + * @var AddressBookViewFactoryInterface */ private $addressBookViewFactory; diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index 06ae64f80..47ca4dc32 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -82,7 +82,7 @@ public function handle(CreateAddress $command): void $address->setPostcode($command->postcode()); $address->setPhoneNumber($command->phoneNumber()); - if ($command->provinceCode()) { + if (null !== $command->provinceCode()) { $province = $this->getProvince($command->provinceCode()); $this->assertProvinceExists($province); $address->setProvinceCode($province->getCode()); diff --git a/tests/DependencyInjection/ConfigurationTest.php b/tests/DependencyInjection/ConfigurationTest.php index b08917ae3..024ccfb35 100644 --- a/tests/DependencyInjection/ConfigurationTest.php +++ b/tests/DependencyInjection/ConfigurationTest.php @@ -52,6 +52,7 @@ public function it_has_view_classes(): void $this->assertProcessedConfigurationEquals([], [ 'view_classes' => [ 'address' => View\AddressView::class, + 'address_book' => View\AddressBookView::class, 'adjustment' => View\AdjustmentView::class, 'cart_item' => View\ItemView::class, 'cart_summary' => View\CartSummaryView::class, From c8849d55fcde8caa7d84a9bd78d8f2b201057eee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 14:00:54 +0100 Subject: [PATCH 10/34] [Address-book] implemented address update and add tests --- src/Command/CreateAddress.php | 100 ++---------- src/Command/UpdateAddress.php | 104 +++++++++++++ .../AddressBook/UpdateAddressAction.php | 75 +++++++-- src/Factory/AddressBookViewFactory.php | 5 +- .../UpdateAddressBookAddressHandler.php | 109 +++++++++++++ src/Model/Address.php | 105 ++++++++++++- src/Request/CreateAddressRequest.php | 27 ++-- src/Request/SetDefaultAddressRequest.php | 2 +- src/Resources/config/routing/address_book.yml | 4 +- .../config/services/actions/address_book.xml | 9 +- src/Resources/config/services/handlers.xml | 8 + .../config/validation/AddressModelRequest.xml | 85 +++++++++++ src/View/AddressBookView.php | 15 ++ tests/Application/app/config/config.yml | 3 +- .../AddressBookCreateAddressApiTest.php | 144 ++++++++++++++++++ .../AddressBookDeleteAddressApiTest.php | 79 ++++++++++ .../AddressBookSetDefaultAddressApiTest.php | 50 ++++++ tests/Controller/AddressBookShowApiTest.php | 28 ++++ .../AddressBookUpdateAddressApiTest.php | 129 ++++++++++++++++ tests/Controller/Utils/ShopUserLoginTrait.php | 2 +- tests/DataFixtures/ORM/address.yml | 45 ++++++ tests/DataFixtures/ORM/customer.yml | 10 +- tests/Request/CreateAddressRequestTest.php | 18 +++ tests/Request/RemoveAddressRequestTest.php | 16 ++ .../Request/SetDefaultAddressRequestTest.php | 16 ++ tests/Request/ShowAddressBookRequestTest.php | 16 ++ .../show_address_book_response.json | 32 ++++ .../Expected/address_book/update_address.json | 14 ++ ...lidation_create_address_book_response.json | 24 +++ ...ress_book_with_wrong_country_response.json | 4 + ...ess_book_with_wrong_province_response.json | 4 + 31 files changed, 1155 insertions(+), 127 deletions(-) create mode 100644 src/Command/UpdateAddress.php create mode 100644 src/Handler/UpdateAddressBookAddressHandler.php create mode 100644 src/Resources/config/validation/AddressModelRequest.xml create mode 100644 tests/Controller/AddressBookCreateAddressApiTest.php create mode 100644 tests/Controller/AddressBookDeleteAddressApiTest.php create mode 100644 tests/Controller/AddressBookSetDefaultAddressApiTest.php create mode 100644 tests/Controller/AddressBookShowApiTest.php create mode 100644 tests/Controller/AddressBookUpdateAddressApiTest.php create mode 100644 tests/DataFixtures/ORM/address.yml create mode 100644 tests/Request/CreateAddressRequestTest.php create mode 100644 tests/Request/RemoveAddressRequestTest.php create mode 100644 tests/Request/SetDefaultAddressRequestTest.php create mode 100644 tests/Request/ShowAddressBookRequestTest.php create mode 100644 tests/Responses/Expected/address_book/show_address_book_response.json create mode 100644 tests/Responses/Expected/address_book/update_address.json create mode 100644 tests/Responses/Expected/address_book/validation_create_address_book_response.json create mode 100644 tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_country_response.json create mode 100644 tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_province_response.json diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index dd35a4b1e..1e28cd8b6 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -4,90 +4,22 @@ namespace Sylius\ShopApiPlugin\Command; -use Webmozart\Assert\Assert; +use Sylius\ShopApiPlugin\Model\Address; final class CreateAddress { /** - * @var string + * @var Address */ - private $firstName; + private $address; /** - * @var string + * CreateAddress constructor. + * @param Address $address */ - private $lastName; - - /** - * @var string - */ - private $company; - - /** - * @var string - */ - private $street; - - /** - * @var string - */ - private $countryCode; - - /** - * @var string - */ - private $provinceCode; - - /** - * @var string - */ - private $city; - - /** - * @var string - */ - private $postcode; - - /** - * @var string - */ - private $phoneNumber; - - /** - * @param $firstName - * @param $lastName - * @param $company - * @param $street - * @param $countryCode - * @param $provinceCode - * @param $city - * @param $postcode - * @param $phoneNumber - */ - public function __construct($firstName, $lastName, $company, $street, $countryCode, $provinceCode, $city, $postcode, $phoneNumber) + public function __construct(Address $address) { - Assert::allString([ - $firstName, - $lastName, - $street, - $countryCode, - $city, - $postcode, - ]); - - Assert::nullOrString($company); - Assert::nullOrString($provinceCode); - Assert::nullOrString($phoneNumber); - - $this->firstName = $firstName; - $this->lastName = $lastName; - $this->company = $company; - $this->street = $street; - $this->countryCode = $countryCode; - $this->provinceCode = $provinceCode; - $this->city = $city; - $this->postcode = $postcode; - $this->phoneNumber = $phoneNumber; + $this->address = $address; } /** @@ -95,7 +27,7 @@ public function __construct($firstName, $lastName, $company, $street, $countryCo */ public function firstName(): string { - return $this->firstName; + return $this->address->firstName(); } /** @@ -103,7 +35,7 @@ public function firstName(): string */ public function lastName(): string { - return $this->lastName; + return $this->address->lastName(); } /** @@ -111,7 +43,7 @@ public function lastName(): string */ public function company(): ?string { - return $this->company; + return $this->address->company(); } /** @@ -119,7 +51,7 @@ public function company(): ?string */ public function street(): string { - return $this->street; + return $this->address->street(); } /** @@ -127,7 +59,7 @@ public function street(): string */ public function countryCode(): string { - return $this->countryCode; + return $this->address->countryCode(); } /** @@ -135,7 +67,7 @@ public function countryCode(): string */ public function provinceCode(): ?string { - return $this->provinceCode; + return $this->address->provinceCode(); } /** @@ -143,7 +75,7 @@ public function provinceCode(): ?string */ public function city(): string { - return $this->city; + return $this->address->city(); } /** @@ -151,7 +83,7 @@ public function city(): string */ public function postcode(): string { - return $this->postcode; + return $this->address->postcode(); } /** @@ -159,6 +91,6 @@ public function postcode(): string */ public function phoneNumber(): ?string { - return $this->phoneNumber; + return $this->address->phoneNumber(); } } diff --git a/src/Command/UpdateAddress.php b/src/Command/UpdateAddress.php new file mode 100644 index 000000000..5a9df20a6 --- /dev/null +++ b/src/Command/UpdateAddress.php @@ -0,0 +1,104 @@ +address = $address; + } + + /** + * @return string + */ + public function id(): string + { + return $this->address->id(); + } + + /** + * @return string + */ + public function firstName(): string + { + return $this->address->firstName(); + } + + /** + * @return string + */ + public function lastName(): string + { + return $this->address->lastName(); + } + + /** + * @return string|null + */ + public function company(): ?string + { + return $this->address->company(); + } + + /** + * @return string + */ + public function street(): string + { + return $this->address->street(); + } + + /** + * @return string + */ + public function countryCode(): string + { + return $this->address->countryCode(); + } + + /** + * @return string|null + */ + public function provinceCode(): ?string + { + return $this->address->provinceCode(); + } + + /** + * @return string + */ + public function city(): string + { + return $this->address->city(); + } + + /** + * @return string + */ + public function postcode(): string + { + return $this->address->postcode(); + } + + /** + * @return string|null + */ + public function phoneNumber(): ?string + { + return $this->address->phoneNumber(); + } +} diff --git a/src/Controller/AddressBook/UpdateAddressAction.php b/src/Controller/AddressBook/UpdateAddressAction.php index 31b34fc34..f2cce89a6 100644 --- a/src/Controller/AddressBook/UpdateAddressAction.php +++ b/src/Controller/AddressBook/UpdateAddressAction.php @@ -6,7 +6,12 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; -use JMS\Serializer\SerializerInterface; +use League\Tactician\CommandBus; +use Sylius\Component\Core\Repository\AddressRepositoryInterface; +use Sylius\ShopApiPlugin\Command\UpdateAddress; +use Sylius\ShopApiPlugin\Factory\AddressBookViewFactoryInterface; +use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; +use Sylius\ShopApiPlugin\Model\Address; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; @@ -20,40 +25,80 @@ final class UpdateAddressAction private $viewHandler; /** - * @var TokenStorageInterface + * @var ValidatorInterface */ - private $tokenStorage; + private $validator; /** - * @var ValidatorInterface + * @var CommandBus */ - private $validator; + private $bus; + + /** + * @var ValidationErrorViewFactoryInterface + */ + private $validationErrorViewFactory; + + /** + * @var AddressBookViewFactoryInterface + */ + private $addressBookViewFactory; + + /** + * @var AddressRepositoryInterface + */ + private $addressRepository; /** - * @var SerializerInterface + * @var TokenStorageInterface */ - private $serializer; + private $tokenStorage; /** * @param ViewHandlerInterface $viewHandler - * @param TokenStorageInterface $tokenStorage * @param ValidatorInterface $validator - * @param SerializerInterface $serializer + * @param CommandBus $bus + * @param ValidationErrorViewFactoryInterface $validationErrorViewFactory + * @param AddressBookViewFactoryInterface $addressViewFactory + * @param AddressRepositoryInterface $addressRepository + * @param TokenStorageInterface $tokenStorage */ public function __construct( ViewHandlerInterface $viewHandler, - TokenStorageInterface $tokenStorage, ValidatorInterface $validator, - SerializerInterface $serializer + CommandBus $bus, + ValidationErrorViewFactoryInterface $validationErrorViewFactory, + AddressBookViewFactoryInterface $addressViewFactory, + AddressRepositoryInterface $addressRepository, + TokenStorageInterface $tokenStorage ) { $this->viewHandler = $viewHandler; - $this->tokenStorage = $tokenStorage; $this->validator = $validator; - $this->serializer = $serializer; + $this->bus = $bus; + $this->validationErrorViewFactory = $validationErrorViewFactory; + $this->addressBookViewFactory = $addressViewFactory; + $this->addressRepository = $addressRepository; + $this->tokenStorage = $tokenStorage; } - public function __invoke(Request $request): Response + public function __invoke(Request $request, $id): Response { - return $this->viewHandler->handle(View::create([], Response::HTTP_OK)); + $addressModel = Address::createFromRequest($request); + + $validationResults = $this->validator->validate($addressModel, null, 'sylius_address_book_update'); + + if (0 !== count($validationResults)) { + return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); + } + + $this->bus->handle(new UpdateAddress($addressModel)); + + $updatedAddress = $this->addressRepository->findOneBy(['id' => $id]); + $customer = $this->tokenStorage->getToken()->getUser()->getCustomer(); + + return $this->viewHandler->handle(View::create( + $this->addressBookViewFactory->create($updatedAddress, $customer), + Response::HTTP_OK) + ); } } diff --git a/src/Factory/AddressBookViewFactory.php b/src/Factory/AddressBookViewFactory.php index adb729c81..00a29e280 100644 --- a/src/Factory/AddressBookViewFactory.php +++ b/src/Factory/AddressBookViewFactory.php @@ -30,10 +30,13 @@ public function create(AddressInterface $address, CustomerInterface $customer): $addressBookView->firstName = $address->getFirstName(); $addressBookView->lastName = $address->getLastName(); $addressBookView->countryCode = $address->getCountryCode(); - $addressBookView->street = $address->getStreet(); $addressBookView->city = $address->getCity(); + $addressBookView->street = $address->getStreet(); $addressBookView->postcode = $address->getPostcode(); $addressBookView->provinceName = $address->getProvinceName(); + $addressBookView->provinceCode = $address->getProvinceCode(); + $addressBookView->company = $address->getCompany(); + $addressBookView->phoneNumber = $address->getPhoneNumber(); $addressBookView->default = $address === $customer->getDefaultAddress(); return $addressBookView; diff --git a/src/Handler/UpdateAddressBookAddressHandler.php b/src/Handler/UpdateAddressBookAddressHandler.php new file mode 100644 index 000000000..746095a31 --- /dev/null +++ b/src/Handler/UpdateAddressBookAddressHandler.php @@ -0,0 +1,109 @@ +addressRepository = $addressRepository; + $this->countryRepository = $countryRepository; + $this->provinceRepository = $provinceRepository; + $this->addressFactory = $addressFactory; + $this->tokenStorage = $tokenStorage; + } + + public function handle(UpdateAddress $command): void + { + /** @var AddressInterface $address */ + $address = $this->addressRepository->findOneBy(['id' => $command->id()]); + $user = $this->tokenStorage->getToken()->getUser(); + + $this->assertCurrentUserIsOwner($address, $user); + $this->assertCountryExists($command->countryCode()); + + /** @var AddressInterface $address */ + $address->setFirstName($command->firstName()); + $address->setLastName($command->lastName()); + $address->setCompany($command->company()); + $address->setStreet($command->street()); + $address->setCountryCode($command->countryCode()); + $address->setCity($command->city()); + $address->setPostcode($command->postcode()); + $address->setPhoneNumber($command->phoneNumber()); + + if (null !== $command->provinceCode() && $command->provinceCode() !== $address->getProvinceCode()) { + $province = $this->provinceRepository->findOneBy(['code' => $command->provinceCode()]); + $this->assertProvinceExists($province); + $address->setProvinceCode($province->getCode()); + $address->setProvinceName($province->getName()); + } + + $this->addressRepository->add($address); + } + + private function assertCountryExists(string $countryCode): void + { + Assert::notNull($this->countryRepository->findOneBy(['code' => $countryCode]), 'Country does not exist.'); + } + + private function assertProvinceExists($province): void + { + Assert::notNull($province, 'Province does not exist.'); + } + + private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) + { + Assert::notNull($address->getCustomer(), 'Address is not associated with any user'); + Assert::eq($address->getCustomer(), $user->getCustomer(), 'Current user is not owner of this address'); + } +} diff --git a/src/Model/Address.php b/src/Model/Address.php index 5ecf058c5..c3969516c 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -4,10 +4,16 @@ namespace Sylius\ShopApiPlugin\Model; +use Symfony\Component\HttpFoundation\Request; use Webmozart\Assert\Assert; final class Address { + /** + * @var integer + */ + private $id; + /** * @var string */ @@ -44,6 +50,22 @@ final class Address private $provinceName; /** + * @var string + */ + private $provinceCode; + + /** + * @var string + */ + private $company; + + /** + * @var string + */ + private $phoneNumber; + + /** + * @param null $id * @param string $firstName * @param string $lastName * @param string $city @@ -51,9 +73,25 @@ final class Address * @param string $countryCode * @param string $postcode * @param string $provinceName - */ - private function __construct($firstName, $lastName, $city, $street, $countryCode, $postcode, $provinceName = null) + * @param null $provinceCode + * @param null $company + * @param null $phoneNumber + */ + private function __construct( + $id = null, + $firstName, + $lastName, + $city, + $street, + $countryCode, + $postcode, + $provinceName = null, + $provinceCode = null, + $phoneNumber = null, + $company = null + ) { + $this->id = $id; $this->firstName = $firstName; $this->lastName = $lastName; $this->city = $city; @@ -61,6 +99,9 @@ private function __construct($firstName, $lastName, $city, $street, $countryCode $this->countryCode = $countryCode; $this->postcode = $postcode; $this->provinceName = $provinceName; + $this->provinceCode = $provinceCode; + $this->phoneNumber = $phoneNumber; + $this->company = $company; } /** @@ -78,16 +119,50 @@ public static function createFromArray(array $address) Assert::keyExists($address, 'postcode'); return new self( + $address['id'] ?? null, $address['firstName'], $address['lastName'], $address['city'], $address['street'], $address['countryCode'], $address['postcode'], - $address['provinceName'] ?? null + $address['provinceName'] ?? null, + $address['provinceCode'] ?? null, + $address['phoneNumber'] ?? null, + $address['company'] ?? null + ); + } + + /** + * @param Request $request + * + * @return Address + */ + public static function createFromRequest(Request $request) + { + return new self( + $request->attributes->get('id') ?? $request->request->get('id'), + $request->request->get('firstName'), + $request->request->get('lastName'), + $request->request->get('city'), + $request->request->get('street'), + $request->request->get('countryCode'), + $request->request->get('postcode'), + $request->request->get('provinceName'), + $request->request->get('provinceCode'), + $request->request->get('phoneNumber'), + $request->request->get('company') ); } + /** + * @return mixed + */ + public function id() + { + return $this->id; + } + /** * @return string */ @@ -143,4 +218,28 @@ public function provinceName() { return $this->provinceName; } + + /** + * @return string + */ + public function provinceCode() + { + return $this->provinceCode; + } + + /** + * @return string + */ + public function company() + { + return $this->company; + } + + /** + * @return string + */ + public function phoneNumber() + { + return $this->phoneNumber; + } } diff --git a/src/Request/CreateAddressRequest.php b/src/Request/CreateAddressRequest.php index 5b452b639..9e4a75146 100644 --- a/src/Request/CreateAddressRequest.php +++ b/src/Request/CreateAddressRequest.php @@ -4,7 +4,9 @@ namespace Sylius\ShopApiPlugin\Request; +use Sylius\Component\Core\Model\AddressInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; +use Sylius\ShopApiPlugin\Model\Address; use Symfony\Component\HttpFoundation\Request; final class CreateAddressRequest @@ -54,6 +56,11 @@ final class CreateAddressRequest */ private $phoneNumber; + /** + * @var AddressInterface + */ + private $address; + /** * CreateAddressRequest constructor. * @@ -63,13 +70,15 @@ public function __construct(Request $request) { $this->firstName = $request->request->get('firstName'); $this->lastName = $request->request->get('lastName'); - $this->company = $request->request->get('company'); + $this->city = $request->request->get('city'); + $this->postcode = $request->request->get('postcode'); $this->street = $request->request->get('street'); $this->countryCode = $request->request->get('countryCode'); $this->provinceCode = $request->request->get('provinceCode'); - $this->city = $request->request->get('city'); - $this->postcode = $request->request->get('postcode'); $this->phoneNumber = $request->request->get('phoneNumber'); + $this->company = $request->request->get('company'); + + $this->address = Address::createFromArray($request->request->all()); } /** @@ -77,16 +86,6 @@ public function __construct(Request $request) */ public function getCommand() { - return new CreateAddress( - $this->firstName, - $this->lastName, - $this->company, - $this->street, - $this->countryCode, - $this->provinceCode, - $this->city, - $this->postcode, - $this->phoneNumber - ); + return new CreateAddress($this->address); } } diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index 6a7cf1df9..b4a1a1b49 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -22,7 +22,7 @@ final class SetDefaultAddressRequest public function __construct(Request $request, ShopUserInterface $user) { - $this->id = $request->request->get('id'); + $this->id = $request->attributes->get('id'); $this->user = $user; } diff --git a/src/Resources/config/routing/address_book.yml b/src/Resources/config/routing/address_book.yml index 818f30bc1..d72685072 100644 --- a/src/Resources/config/routing/address_book.yml +++ b/src/Resources/config/routing/address_book.yml @@ -17,14 +17,14 @@ sylius_shop_remove_address_book_entry: _controller: sylius.shop_api_plugin.controller.address_book.remove_address_action sylius_shop_set_default_address: - path: /address-book/default + path: /address-book/{id}/default methods: [PATCH] defaults: _controller: sylius.shop_api_plugin.controller.address_book.set_default_address_action sylius_shop_update_address_book_entry: path: /address-book/{id} - methods: [PUT, PATCH] + methods: [PUT] defaults: _controller: sylius.shop_api_plugin.controller.address_book.update_address_action diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index d60b39602..35c4b93f0 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -30,11 +30,12 @@ class="Sylius\ShopApiPlugin\Controller\AddressBook\UpdateAddressAction" > - - - - + + + + + + + + + + + + + diff --git a/src/Resources/config/validation/AddressModelRequest.xml b/src/Resources/config/validation/AddressModelRequest.xml new file mode 100644 index 000000000..fb217a208 --- /dev/null +++ b/src/Resources/config/validation/AddressModelRequest.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/View/AddressBookView.php b/src/View/AddressBookView.php index 0e622fcde..4e83a4fc8 100644 --- a/src/View/AddressBookView.php +++ b/src/View/AddressBookView.php @@ -46,6 +46,21 @@ class AddressBookView */ public $provinceName; + /** + * @var string + */ + public $provinceCode; + + /** + * @var string + */ + public $company; + + /** + * @var string + */ + public $phoneNumber; + /** * @var bool */ diff --git a/tests/Application/app/config/config.yml b/tests/Application/app/config/config.yml index 8d6f145a0..ad4f4c6e0 100644 --- a/tests/Application/app/config/config.yml +++ b/tests/Application/app/config/config.yml @@ -36,7 +36,8 @@ framework: doctrine: dbal: driver: "pdo_sqlite" - path: "%kernel.cache_dir%/db.sql" +# path: "%kernel.cache_dir%/db.sql" + path: "/run/shm/sylius/cache/test/db.sql" charset: UTF8 fos_rest: diff --git a/tests/Controller/AddressBookCreateAddressApiTest.php b/tests/Controller/AddressBookCreateAddressApiTest.php new file mode 100644 index 000000000..e4a05d010 --- /dev/null +++ b/tests/Controller/AddressBookCreateAddressApiTest.php @@ -0,0 +1,144 @@ + 'application/json', 'ACCEPT' => 'application/json']; + + /** + * @test + */ + public function it_allows_user_to_add_new_address_to_address_book() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + $data = +<<client->request('POST', '/shop-api/address-book', [], [], self::$acceptAndContentTypeHeader, $data); + + $response = $this->client->getResponse(); + $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); + + /** @var CustomerRepositoryInterface $customerRepository */ + $customerRepository = $this->get('sylius.repository.customer'); + /** @var Customer $customer */ + $customer = $customerRepository->findOneBy(['email' => 'oliver@queen.com']); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var AddressInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Kupreska 12']); + + Assert::assertSame($address->getCustomer(), $customer); + Assert::assertNotNull($address); + Assert::assertTrue($customer->hasAddress($address)); + } + + /** + * @test + */ + public function it_does_not_allow_user_to_add_new_address_to_address_book_without_passing_required_data() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + $data = +<<client->request('POST', '/shop-api/address-book', [], [], self::$acceptAndContentTypeHeader, $data); + + $response = $this->client->getResponse(); + $this->assertResponse($response, 'address_book/validation_create_address_book_response', Response::HTTP_BAD_REQUEST); + } + + /** + * @test + */ + public function it_does_not_allow_user_to_add_new_address_to_address_book_without_passing_correct_country_code() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + $data = +<<client->request('POST', '/shop-api/address-book', [], [], self::$acceptAndContentTypeHeader, $data); + + $response = $this->client->getResponse(); + $this->assertResponse($response, 'address_book/validation_create_address_book_with_wrong_country_response', Response::HTTP_INTERNAL_SERVER_ERROR); + } + + /** + * @test + */ + public function it_does_not_allow_user_to_add_new_address_to_address_book_without_passing_correct_province_code() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + $data = + <<client->request('POST', '/shop-api/address-book', [], [], self::$acceptAndContentTypeHeader, $data); + + $response = $this->client->getResponse(); + $this->assertResponse($response, 'address_book/validation_create_address_book_with_wrong_province_response', Response::HTTP_INTERNAL_SERVER_ERROR); + } +} \ No newline at end of file diff --git a/tests/Controller/AddressBookDeleteAddressApiTest.php b/tests/Controller/AddressBookDeleteAddressApiTest.php new file mode 100644 index 000000000..7d3e740fd --- /dev/null +++ b/tests/Controller/AddressBookDeleteAddressApiTest.php @@ -0,0 +1,79 @@ + 'application/json', 'ACCEPT' => 'application/json']; + + /** + * @test + */ + public function it_deletes_address_from_address_book() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var AddressInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Kupreska']); + + $this->client->request('DELETE', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$acceptAndContentTypeHeader); + $response = $this->client->getResponse(); + + $address = $addressRepository->findOneBy(['street' => 'Kupreska']); + Assert::assertNull($address); + + $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); + } + + /** + * @test + */ + public function it_returns_bad_request_exception_if_address_has_not_been_found() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + $this->client->request('DELETE',sprintf("/shop-api/address-book/-1"), [], [], self::$acceptAndContentTypeHeader); + $response = $this->client->getResponse(); + + $this->assertResponseCode($response, Response::HTTP_BAD_REQUEST); + } + + /** + * @test + */ + public function it_validates_if_current_user_is_owner_of_address() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var AddressInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Vukovarska']); + + $this->client->request('DELETE', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$acceptAndContentTypeHeader); + $response = $this->client->getResponse(); + + $this->assertResponseCode($response, Response::HTTP_INTERNAL_SERVER_ERROR); + } +} \ No newline at end of file diff --git a/tests/Controller/AddressBookSetDefaultAddressApiTest.php b/tests/Controller/AddressBookSetDefaultAddressApiTest.php new file mode 100644 index 000000000..a9ce8832d --- /dev/null +++ b/tests/Controller/AddressBookSetDefaultAddressApiTest.php @@ -0,0 +1,50 @@ + 'application/json', 'ACCEPT' => 'application/json']; + + /** + * @test + */ + public function it_sets_given_address_as_default() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var ResourceInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Kupreska']); + + $this->client->request('PATCH', sprintf("/shop-api/address-book/%s/default", $address->getId()), [], [], self::$acceptAndContentTypeHeader); + + $response = $this->client->getResponse(); + $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); + + /** @var UserRepositoryInterface $userRepository */ + $userRepository = $this->get('sylius.repository.shop_user'); + /** @var ShopUser $address */ + $shopUser = $userRepository->findOneByEmail("oliver@queen.com"); + + Assert::assertEquals( + $shopUser->getCustomer()->getDefaultAddress(), + $address + ); + } +} \ No newline at end of file diff --git a/tests/Controller/AddressBookShowApiTest.php b/tests/Controller/AddressBookShowApiTest.php new file mode 100644 index 000000000..6b3a5db1a --- /dev/null +++ b/tests/Controller/AddressBookShowApiTest.php @@ -0,0 +1,28 @@ +loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + $this->client->request('GET', '/shop-api/address-book', [], [], ['ACCEPT' => 'application/json']); + $response = $this->client->getResponse(); + + $this->assertResponse($response, 'address_book/show_address_book_response', Response::HTTP_OK); + } +} \ No newline at end of file diff --git a/tests/Controller/AddressBookUpdateAddressApiTest.php b/tests/Controller/AddressBookUpdateAddressApiTest.php new file mode 100644 index 000000000..e63036fcb --- /dev/null +++ b/tests/Controller/AddressBookUpdateAddressApiTest.php @@ -0,0 +1,129 @@ + 'application/json']; + + /** + * @test + */ + public function it_updates_address_in_address_book() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var AddressInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Kupreska']); + + $data = + <<client->request('PUT', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$contentTypeHeader, $data); + $response = $this->client->getResponse(); + + $this->assertResponse($response, 'address_book/update_address', Response::HTTP_OK); + + /** @var AddressInterface $updatedAddress */ + $updatedAddress = $addressRepository->findOneBy(['id' => $address->getId()]); + Assert::assertEquals($updatedAddress->getFirstName(), "New name"); + Assert::assertEquals($updatedAddress->getLastName(), "New lastName"); + Assert::assertEquals($updatedAddress->getCompany(), "Locastic"); + Assert::assertEquals($updatedAddress->getCity(), "New city"); + Assert::assertEquals($updatedAddress->getPostcode(), "2000"); + Assert::assertEquals($updatedAddress->getProvinceCode(), "GB-WLS"); + Assert::assertEquals($updatedAddress->getPhoneNumber(), "0918972132"); + } + + /** + * @test + */ + public function it_does_not_allow_to_update_address_if_country_or_province_code_are_not_valid() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var AddressInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Kupreska']); + + $data = + <<client->request('PUT', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$contentTypeHeader, $data); + $response = $this->client->getResponse(); + + $this->assertResponseCode($response, Response::HTTP_INTERNAL_SERVER_ERROR); + } + + /** + * @test + */ + public function it_does_not_allow_to_update_address_without_passing_required_data() + { + $this->loadFixturesFromFile('customer.yml'); + $this->loadFixturesFromFile('country.yml'); + $this->loadFixturesFromFile('address.yml'); + $this->logInUser('oliver@queen.com', '123pa$$word'); + + /** @var AddressRepositoryInterface $addressRepository */ + $addressRepository = $this->get('sylius.repository.address'); + /** @var AddressInterface $address */ + $address = $addressRepository->findOneBy(['street' => 'Kupreska']); + + $data = + <<client->request('PUT', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$contentTypeHeader, $data); + $response = $this->client->getResponse(); + + $this->assertResponseCode($response, Response::HTTP_BAD_REQUEST); + } +} \ No newline at end of file diff --git a/tests/Controller/Utils/ShopUserLoginTrait.php b/tests/Controller/Utils/ShopUserLoginTrait.php index 005d91661..5a846a513 100644 --- a/tests/Controller/Utils/ShopUserLoginTrait.php +++ b/tests/Controller/Utils/ShopUserLoginTrait.php @@ -13,7 +13,7 @@ trait ShopUserLoginTrait /** @var Client */ protected $client; - protected function logInUser($username, $password) + protected function logInUser(string $username, string $password): void { $data = << Date: Mon, 30 Oct 2017 14:06:54 +0100 Subject: [PATCH 11/34] [Address-book] Refactored create address, now using address model instead of request class --- .../AddressBook/CreateAddressAction.php | 8 +- src/Request/CreateAddressRequest.php | 91 ------------------- .../config/validation/AddressModelRequest.xml | 11 +++ 3 files changed, 16 insertions(+), 94 deletions(-) delete mode 100644 src/Request/CreateAddressRequest.php diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index bb9d501ab..66a50fbe6 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -7,7 +7,9 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; +use Sylius\ShopApiPlugin\Command\CreateAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; +use Sylius\ShopApiPlugin\Model\Address; use Sylius\ShopApiPlugin\Request\CreateAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -62,15 +64,15 @@ public function __construct( */ public function __invoke(Request $request): Response { - $createAddressRequest = new CreateAddressRequest($request); + $addressModel = Address::createFromRequest($request); - $validationResults = $this->validator->validate($createAddressRequest); + $validationResults = $this->validator->validate($addressModel, null, 'sylius_address_book_create'); if (0 !== count($validationResults)) { return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - $this->bus->handle($createAddressRequest->getCommand()); + $this->bus->handle(new CreateAddress($addressModel)); return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } diff --git a/src/Request/CreateAddressRequest.php b/src/Request/CreateAddressRequest.php deleted file mode 100644 index 9e4a75146..000000000 --- a/src/Request/CreateAddressRequest.php +++ /dev/null @@ -1,91 +0,0 @@ -firstName = $request->request->get('firstName'); - $this->lastName = $request->request->get('lastName'); - $this->city = $request->request->get('city'); - $this->postcode = $request->request->get('postcode'); - $this->street = $request->request->get('street'); - $this->countryCode = $request->request->get('countryCode'); - $this->provinceCode = $request->request->get('provinceCode'); - $this->phoneNumber = $request->request->get('phoneNumber'); - $this->company = $request->request->get('company'); - - $this->address = Address::createFromArray($request->request->all()); - } - - /** - * @return CreateAddress - */ - public function getCommand() - { - return new CreateAddress($this->address); - } -} diff --git a/src/Resources/config/validation/AddressModelRequest.xml b/src/Resources/config/validation/AddressModelRequest.xml index fb217a208..6b0ab9b3c 100644 --- a/src/Resources/config/validation/AddressModelRequest.xml +++ b/src/Resources/config/validation/AddressModelRequest.xml @@ -15,6 +15,7 @@ + @@ -22,12 +23,14 @@ + + @@ -35,17 +38,20 @@ + + + @@ -53,12 +59,14 @@ + + @@ -66,12 +74,14 @@ + + @@ -79,6 +89,7 @@ + From 31f67e3126e9ce1931ac54ddee6af425816e30b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 14:11:41 +0100 Subject: [PATCH 12/34] [Address-book] Apply ecs fix --- src/Command/CreateAddress.php | 1 + src/Command/UpdateAddress.php | 1 + .../AddressBook/CreateAddressAction.php | 2 +- .../AddressBook/ShowAddressBookAction.php | 1 - .../UpdateAddressBookAddressHandler.php | 2 +- src/Model/Address.php | 5 ++-- .../AddressBookCreateAddressApiTest.php | 4 ++- .../AddressBookDeleteAddressApiTest.php | 11 ++++---- .../AddressBookSetDefaultAddressApiTest.php | 8 ++++-- tests/Controller/AddressBookShowApiTest.php | 4 ++- .../AddressBookUpdateAddressApiTest.php | 28 ++++++++++--------- tests/Request/CreateAddressRequestTest.php | 3 +- tests/Request/RemoveAddressRequestTest.php | 5 ++-- .../Request/SetDefaultAddressRequestTest.php | 5 ++-- tests/Request/ShowAddressBookRequestTest.php | 5 ++-- 15 files changed, 48 insertions(+), 37 deletions(-) diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index 1e28cd8b6..3088f1a1c 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -15,6 +15,7 @@ final class CreateAddress /** * CreateAddress constructor. + * * @param Address $address */ public function __construct(Address $address) diff --git a/src/Command/UpdateAddress.php b/src/Command/UpdateAddress.php index 5a9df20a6..c6e846740 100644 --- a/src/Command/UpdateAddress.php +++ b/src/Command/UpdateAddress.php @@ -15,6 +15,7 @@ final class UpdateAddress /** * CreateAddress constructor. + * * @param Address $address */ public function __construct(Address $address) diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index 66a50fbe6..201be0701 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -10,7 +10,6 @@ use Sylius\ShopApiPlugin\Command\CreateAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; use Sylius\ShopApiPlugin\Model\Address; -use Sylius\ShopApiPlugin\Request\CreateAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Validator\Validator\ValidatorInterface; @@ -77,3 +76,4 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } } + diff --git a/src/Controller/AddressBook/ShowAddressBookAction.php b/src/Controller/AddressBook/ShowAddressBookAction.php index 1fd809008..0f03c793f 100644 --- a/src/Controller/AddressBook/ShowAddressBookAction.php +++ b/src/Controller/AddressBook/ShowAddressBookAction.php @@ -9,7 +9,6 @@ use Sylius\Component\Core\Model\Customer; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\ShopApiPlugin\Factory\AddressBookViewFactoryInterface; -use Sylius\ShopApiPlugin\Factory\AddressViewFactory; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; diff --git a/src/Handler/UpdateAddressBookAddressHandler.php b/src/Handler/UpdateAddressBookAddressHandler.php index 746095a31..75426ff42 100644 --- a/src/Handler/UpdateAddressBookAddressHandler.php +++ b/src/Handler/UpdateAddressBookAddressHandler.php @@ -81,7 +81,7 @@ public function handle(UpdateAddress $command): void $address->setPostcode($command->postcode()); $address->setPhoneNumber($command->phoneNumber()); - if (null !== $command->provinceCode() && $command->provinceCode() !== $address->getProvinceCode()) { + if (null !== $command->provinceCode() && $command->provinceCode() !== $address->getProvinceCode()) { $province = $this->provinceRepository->findOneBy(['code' => $command->provinceCode()]); $this->assertProvinceExists($province); $address->setProvinceCode($province->getCode()); diff --git a/src/Model/Address.php b/src/Model/Address.php index c3969516c..7de038273 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -10,7 +10,7 @@ final class Address { /** - * @var integer + * @var int */ private $id; @@ -89,8 +89,7 @@ private function __construct( $provinceCode = null, $phoneNumber = null, $company = null - ) - { + ) { $this->id = $id; $this->firstName = $firstName; $this->lastName = $lastName; diff --git a/tests/Controller/AddressBookCreateAddressApiTest.php b/tests/Controller/AddressBookCreateAddressApiTest.php index e4a05d010..0731a2dcf 100644 --- a/tests/Controller/AddressBookCreateAddressApiTest.php +++ b/tests/Controller/AddressBookCreateAddressApiTest.php @@ -1,5 +1,7 @@ client->getResponse(); $this->assertResponse($response, 'address_book/validation_create_address_book_with_wrong_province_response', Response::HTTP_INTERNAL_SERVER_ERROR); } -} \ No newline at end of file +} diff --git a/tests/Controller/AddressBookDeleteAddressApiTest.php b/tests/Controller/AddressBookDeleteAddressApiTest.php index 7d3e740fd..799c38e74 100644 --- a/tests/Controller/AddressBookDeleteAddressApiTest.php +++ b/tests/Controller/AddressBookDeleteAddressApiTest.php @@ -1,7 +1,8 @@ findOneBy(['street' => 'Kupreska']); - $this->client->request('DELETE', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$acceptAndContentTypeHeader); + $this->client->request('DELETE', sprintf('/shop-api/address-book/%s', $address->getId()), [], [], self::$acceptAndContentTypeHeader); $response = $this->client->getResponse(); $address = $addressRepository->findOneBy(['street' => 'Kupreska']); @@ -50,7 +51,7 @@ public function it_returns_bad_request_exception_if_address_has_not_been_found() $this->loadFixturesFromFile('address.yml'); $this->logInUser('oliver@queen.com', '123pa$$word'); - $this->client->request('DELETE',sprintf("/shop-api/address-book/-1"), [], [], self::$acceptAndContentTypeHeader); + $this->client->request('DELETE', sprintf('/shop-api/address-book/-1'), [], [], self::$acceptAndContentTypeHeader); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_BAD_REQUEST); @@ -71,9 +72,9 @@ public function it_validates_if_current_user_is_owner_of_address() /** @var AddressInterface $address */ $address = $addressRepository->findOneBy(['street' => 'Vukovarska']); - $this->client->request('DELETE', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$acceptAndContentTypeHeader); + $this->client->request('DELETE', sprintf('/shop-api/address-book/%s', $address->getId()), [], [], self::$acceptAndContentTypeHeader); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_INTERNAL_SERVER_ERROR); } -} \ No newline at end of file +} diff --git a/tests/Controller/AddressBookSetDefaultAddressApiTest.php b/tests/Controller/AddressBookSetDefaultAddressApiTest.php index a9ce8832d..20dc23132 100644 --- a/tests/Controller/AddressBookSetDefaultAddressApiTest.php +++ b/tests/Controller/AddressBookSetDefaultAddressApiTest.php @@ -1,5 +1,7 @@ findOneBy(['street' => 'Kupreska']); - $this->client->request('PATCH', sprintf("/shop-api/address-book/%s/default", $address->getId()), [], [], self::$acceptAndContentTypeHeader); + $this->client->request('PATCH', sprintf('/shop-api/address-book/%s/default', $address->getId()), [], [], self::$acceptAndContentTypeHeader); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); @@ -40,11 +42,11 @@ public function it_sets_given_address_as_default() /** @var UserRepositoryInterface $userRepository */ $userRepository = $this->get('sylius.repository.shop_user'); /** @var ShopUser $address */ - $shopUser = $userRepository->findOneByEmail("oliver@queen.com"); + $shopUser = $userRepository->findOneByEmail('oliver@queen.com'); Assert::assertEquals( $shopUser->getCustomer()->getDefaultAddress(), $address ); } -} \ No newline at end of file +} diff --git a/tests/Controller/AddressBookShowApiTest.php b/tests/Controller/AddressBookShowApiTest.php index 6b3a5db1a..2045e1d51 100644 --- a/tests/Controller/AddressBookShowApiTest.php +++ b/tests/Controller/AddressBookShowApiTest.php @@ -1,5 +1,7 @@ assertResponse($response, 'address_book/show_address_book_response', Response::HTTP_OK); } -} \ No newline at end of file +} diff --git a/tests/Controller/AddressBookUpdateAddressApiTest.php b/tests/Controller/AddressBookUpdateAddressApiTest.php index e63036fcb..cf7765a8e 100644 --- a/tests/Controller/AddressBookUpdateAddressApiTest.php +++ b/tests/Controller/AddressBookUpdateAddressApiTest.php @@ -1,5 +1,7 @@ 'application/json']; /** - * @test - */ + * @test + */ public function it_updates_address_in_address_book() { $this->loadFixturesFromFile('customer.yml'); @@ -44,20 +46,20 @@ public function it_updates_address_in_address_book() "phoneNumber": "0918972132" } EOT; - $this->client->request('PUT', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$contentTypeHeader, $data); + $this->client->request('PUT', sprintf('/shop-api/address-book/%s', $address->getId()), [], [], self::$contentTypeHeader, $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'address_book/update_address', Response::HTTP_OK); /** @var AddressInterface $updatedAddress */ $updatedAddress = $addressRepository->findOneBy(['id' => $address->getId()]); - Assert::assertEquals($updatedAddress->getFirstName(), "New name"); - Assert::assertEquals($updatedAddress->getLastName(), "New lastName"); - Assert::assertEquals($updatedAddress->getCompany(), "Locastic"); - Assert::assertEquals($updatedAddress->getCity(), "New city"); - Assert::assertEquals($updatedAddress->getPostcode(), "2000"); - Assert::assertEquals($updatedAddress->getProvinceCode(), "GB-WLS"); - Assert::assertEquals($updatedAddress->getPhoneNumber(), "0918972132"); + Assert::assertEquals($updatedAddress->getFirstName(), 'New name'); + Assert::assertEquals($updatedAddress->getLastName(), 'New lastName'); + Assert::assertEquals($updatedAddress->getCompany(), 'Locastic'); + Assert::assertEquals($updatedAddress->getCity(), 'New city'); + Assert::assertEquals($updatedAddress->getPostcode(), '2000'); + Assert::assertEquals($updatedAddress->getProvinceCode(), 'GB-WLS'); + Assert::assertEquals($updatedAddress->getPhoneNumber(), '0918972132'); } /** @@ -89,7 +91,7 @@ public function it_does_not_allow_to_update_address_if_country_or_province_code_ "phoneNumber": "0918972132" } EOT; - $this->client->request('PUT', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$contentTypeHeader, $data); + $this->client->request('PUT', sprintf('/shop-api/address-book/%s', $address->getId()), [], [], self::$contentTypeHeader, $data); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_INTERNAL_SERVER_ERROR); @@ -121,9 +123,9 @@ public function it_does_not_allow_to_update_address_without_passing_required_dat "postcode": "", } EOT; - $this->client->request('PUT', sprintf("/shop-api/address-book/%s", $address->getId()), [], [], self::$contentTypeHeader, $data); + $this->client->request('PUT', sprintf('/shop-api/address-book/%s', $address->getId()), [], [], self::$contentTypeHeader, $data); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_BAD_REQUEST); } -} \ No newline at end of file +} diff --git a/tests/Request/CreateAddressRequestTest.php b/tests/Request/CreateAddressRequestTest.php index d6048ca81..a0698fe98 100644 --- a/tests/Request/CreateAddressRequestTest.php +++ b/tests/Request/CreateAddressRequestTest.php @@ -13,6 +13,5 @@ class CreateAddressRequestTest extends TestCase */ public function it_creates_create_address_command() { - // } -} \ No newline at end of file +} diff --git a/tests/Request/RemoveAddressRequestTest.php b/tests/Request/RemoveAddressRequestTest.php index aa2a3fadb..ba2d538bd 100644 --- a/tests/Request/RemoveAddressRequestTest.php +++ b/tests/Request/RemoveAddressRequestTest.php @@ -1,5 +1,7 @@ Date: Mon, 30 Oct 2017 14:39:14 +0100 Subject: [PATCH 13/34] [Address-book] Fix tests --- tests/Controller/AddressBookSetDefaultAddressApiTest.php | 9 ++++----- .../address_book/show_address_book_response.json | 9 +++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/tests/Controller/AddressBookSetDefaultAddressApiTest.php b/tests/Controller/AddressBookSetDefaultAddressApiTest.php index 20dc23132..8accb38a9 100644 --- a/tests/Controller/AddressBookSetDefaultAddressApiTest.php +++ b/tests/Controller/AddressBookSetDefaultAddressApiTest.php @@ -6,11 +6,11 @@ use Lakion\ApiTestCase\JsonApiTestCase; use PHPUnit\Framework\Assert; -use Sylius\Component\Core\Model\ShopUser; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\User\Repository\UserRepositoryInterface; use Symfony\Component\HttpFoundation\Response; +use Sylius\Component\Core\Model\ShopUser; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; class AddressBookSetDefaultAddressApiTest extends JsonApiTestCase @@ -35,18 +35,17 @@ public function it_sets_given_address_as_default() $address = $addressRepository->findOneBy(['street' => 'Kupreska']); $this->client->request('PATCH', sprintf('/shop-api/address-book/%s/default', $address->getId()), [], [], self::$acceptAndContentTypeHeader); - $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); /** @var UserRepositoryInterface $userRepository */ $userRepository = $this->get('sylius.repository.shop_user'); /** @var ShopUser $address */ - $shopUser = $userRepository->findOneByEmail('oliver@queen.com'); + $shopUser = $userRepository->findOneBy(['username' => 'oliver@queen.com']); Assert::assertEquals( - $shopUser->getCustomer()->getDefaultAddress(), - $address + $shopUser->getCustomer()->getDefaultAddress()->getId(), + $address->getId() ); } } diff --git a/tests/Responses/Expected/address_book/show_address_book_response.json b/tests/Responses/Expected/address_book/show_address_book_response.json index c88877fed..97352b594 100644 --- a/tests/Responses/Expected/address_book/show_address_book_response.json +++ b/tests/Responses/Expected/address_book/show_address_book_response.json @@ -7,6 +7,9 @@ "street": "McGlynn Island", "city": "Klingside", "postcode": "33553", + "provinceCode": "Scotland", + "company": "Sylius", + "phoneNumber": "349713", "default": false }, { @@ -17,6 +20,9 @@ "street": "Kupreska", "city": "Klingside", "postcode": "33553", + "provinceCode": "Scotland", + "company": "Locastic", + "phoneNumber": "349713", "default": false }, { @@ -27,6 +33,9 @@ "street": "Lurline Springs", "city": "Klingside", "postcode": "33553", + "provinceCode": "Scotland", + "company": "Locastic", + "phoneNumber": "349713", "default": false } ] \ No newline at end of file From 79718f8ddf0f06d14485ba829bf1d3332304e102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 15:49:46 +0100 Subject: [PATCH 14/34] [Address-book] Move getting current user from request to handler --- src/Command/RemoveAddress.php | 11 +---------- src/Handler/RemoveAddressHandler.php | 14 ++++++++++++-- src/Request/RemoveAddressRequest.php | 11 ++--------- src/Resources/config/services/handlers.xml | 1 + ....php => AddressBookRemoveAddressApiTest.php} | 2 +- tests/Request/CreateAddressRequestTest.php | 17 ----------------- tests/Request/ShowAddressBookRequestTest.php | 6 ++++++ 7 files changed, 23 insertions(+), 39 deletions(-) rename tests/Controller/{AddressBookDeleteAddressApiTest.php => AddressBookRemoveAddressApiTest.php} (97%) delete mode 100644 tests/Request/CreateAddressRequestTest.php diff --git a/src/Command/RemoveAddress.php b/src/Command/RemoveAddress.php index 71fe97530..97f883973 100644 --- a/src/Command/RemoveAddress.php +++ b/src/Command/RemoveAddress.php @@ -4,8 +4,6 @@ namespace Sylius\ShopApiPlugin\Command; -use Sylius\Component\Core\Model\ShopUserInterface; - class RemoveAddress { /** @@ -13,18 +11,11 @@ class RemoveAddress */ public $id; - /** - * @var ShopUserInterface - */ - public $user; - /** * @param $id - * @param ShopUserInterface $user */ - public function __construct($id, ShopUserInterface $user) + public function __construct($id) { $this->id = $id; - $this->user = $user; } } diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 0bfce7d14..34cfeebaf 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -10,6 +10,7 @@ use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; final class RemoveAddressHandler @@ -24,18 +25,27 @@ final class RemoveAddressHandler */ private $orderRepository; - public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository) + /** + * @var TokenStorageInterface + */ + private $tokenStorage; + + public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, TokenStorageInterface $tokenStorage) { $this->addressRepository = $addressRepository; $this->orderRepository = $orderRepository; + $this->tokenStorage = $tokenStorage; } public function handle(RemoveAddress $removeAddress) { + /** @var ShopUserInterface $user */ + $user = $this->tokenStorage->getToken()->getUser(); + /** @var AddressInterface $address */ $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id]); - $this->assertCurrentUserIsOwner($address, $removeAddress->user); + $this->assertCurrentUserIsOwner($address, $user); $this->assertOrderWithAddressNotExists($address); $this->addressRepository->remove($address); diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php index 030709dcd..052a1e3fe 100644 --- a/src/Request/RemoveAddressRequest.php +++ b/src/Request/RemoveAddressRequest.php @@ -4,7 +4,6 @@ namespace Sylius\ShopApiPlugin\Request; -use Sylius\Component\User\Model\UserInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; use Symfony\Component\HttpFoundation\Request; @@ -15,19 +14,13 @@ final class RemoveAddressRequest */ private $id; - /** - * @var UserInterface - */ - private $user; - - public function __construct(Request $request, UserInterface $user) + public function __construct(Request $request) { $this->id = $request->attributes->get('id'); - $this->user = $user; } public function getCommand() { - return new RemoveAddress($this->id, $this->user); + return new RemoveAddress($this->id); } } diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index 17fa23994..b9b68d636 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -165,6 +165,7 @@ + diff --git a/tests/Controller/AddressBookDeleteAddressApiTest.php b/tests/Controller/AddressBookRemoveAddressApiTest.php similarity index 97% rename from tests/Controller/AddressBookDeleteAddressApiTest.php rename to tests/Controller/AddressBookRemoveAddressApiTest.php index 799c38e74..5cf5247cd 100644 --- a/tests/Controller/AddressBookDeleteAddressApiTest.php +++ b/tests/Controller/AddressBookRemoveAddressApiTest.php @@ -11,7 +11,7 @@ use Symfony\Component\HttpFoundation\Response; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; -class AddressBookDeleteAddressApiTest extends JsonApiTestCase +class AddressBookRemoveAddressApiTest extends JsonApiTestCase { use ShopUserLoginTrait; diff --git a/tests/Request/CreateAddressRequestTest.php b/tests/Request/CreateAddressRequestTest.php deleted file mode 100644 index a0698fe98..000000000 --- a/tests/Request/CreateAddressRequestTest.php +++ /dev/null @@ -1,17 +0,0 @@ - '1'])); + + $this->assertEquals($removeAddressRequest->getCommand(), new RemoveAddress('1')); } } From e3b109a77508103a83f7121b0309ec1c5084b44d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 15:52:17 +0100 Subject: [PATCH 15/34] [Address-book] Remove address request test --- tests/Request/RemoveAddressRequestTest.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/Request/RemoveAddressRequestTest.php b/tests/Request/RemoveAddressRequestTest.php index ba2d538bd..d10eb4b5b 100644 --- a/tests/Request/RemoveAddressRequestTest.php +++ b/tests/Request/RemoveAddressRequestTest.php @@ -5,6 +5,9 @@ namespace Sylius\ShopApiPlugin\Controller\AddressBook; use PHPUnit\Framework\TestCase; +use Sylius\ShopApiPlugin\Command\RemoveAddress; +use Sylius\ShopApiPlugin\Request\RemoveAddressRequest; +use Symfony\Component\HttpFoundation\Request; class RemoveAddressRequestTest extends TestCase { @@ -13,5 +16,8 @@ class RemoveAddressRequestTest extends TestCase */ public function it_creates_remove_address_command() { + $removeAddressRequest = new RemoveAddressRequest(new Request([], [], ['id' => '1'])); + + $this->assertEquals($removeAddressRequest->getCommand(), new RemoveAddress('1')); } -} +} \ No newline at end of file From 13930a7a9d8108298fc3853b0fbd0b51481767d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 15:53:20 +0100 Subject: [PATCH 16/34] [Address-book] Remove show address request test --- tests/Request/ShowAddressBookRequestTest.php | 23 -------------------- 1 file changed, 23 deletions(-) delete mode 100644 tests/Request/ShowAddressBookRequestTest.php diff --git a/tests/Request/ShowAddressBookRequestTest.php b/tests/Request/ShowAddressBookRequestTest.php deleted file mode 100644 index d03cb4698..000000000 --- a/tests/Request/ShowAddressBookRequestTest.php +++ /dev/null @@ -1,23 +0,0 @@ - '1'])); - - $this->assertEquals($removeAddressRequest->getCommand(), new RemoveAddress('1')); - } -} From 1f21f6821bd10a3cc5a6dfef2ed8a72d3b036887 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 16:01:22 +0100 Subject: [PATCH 17/34] [Address-book] Move user from SetDefaultAddressRequest to corresponding handler --- src/Command/SetDefaultAddress.php | 8 +------ .../AddressBook/RemoveAddressAction.php | 13 ++--------- .../AddressBook/SetDefaultAddress.php | 12 ++-------- src/Handler/SetDefaultAddressHandler.php | 23 +++++++++++++++---- src/Request/SetDefaultAddressRequest.php | 10 ++------ .../config/services/actions/address_book.xml | 2 -- src/Resources/config/services/handlers.xml | 1 + .../Request/SetDefaultAddressRequestTest.php | 8 ++++++- 8 files changed, 34 insertions(+), 43 deletions(-) diff --git a/src/Command/SetDefaultAddress.php b/src/Command/SetDefaultAddress.php index 5c17d78bc..9a4f91317 100644 --- a/src/Command/SetDefaultAddress.php +++ b/src/Command/SetDefaultAddress.php @@ -13,14 +13,8 @@ class SetDefaultAddress */ public $id; - /** - * @var ShopUserInterface - */ - public $user; - - public function __construct($id, ShopUserInterface $user) + public function __construct($id) { $this->id = $id; - $this->user = $user; } } diff --git a/src/Controller/AddressBook/RemoveAddressAction.php b/src/Controller/AddressBook/RemoveAddressAction.php index a8ebc0efe..c837acf0e 100644 --- a/src/Controller/AddressBook/RemoveAddressAction.php +++ b/src/Controller/AddressBook/RemoveAddressAction.php @@ -11,7 +11,6 @@ use Sylius\ShopApiPlugin\Request\RemoveAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; final class RemoveAddressAction @@ -36,35 +35,27 @@ final class RemoveAddressAction */ private $bus; - /** - * @var TokenStorageInterface - */ - private $tokenStorage; - /** * @param ViewHandlerInterface $viewHandler * @param ValidatorInterface $validator * @param ValidationErrorViewFactory $validationErrorViewFactory * @param CommandBus $bus - * @param TokenStorageInterface $tokenStorage */ public function __construct( ViewHandlerInterface $viewHandler, ValidatorInterface $validator, ValidationErrorViewFactory $validationErrorViewFactory, - CommandBus $bus, - TokenStorageInterface $tokenStorage + CommandBus $bus ) { $this->viewHandler = $viewHandler; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; $this->bus = $bus; - $this->tokenStorage = $tokenStorage; } public function __invoke(Request $request): Response { - $removeAddressRequest = new RemoveAddressRequest($request, $this->tokenStorage->getToken()->getUser()); + $removeAddressRequest = new RemoveAddressRequest($request); $validationResults = $this->validator->validate($removeAddressRequest); diff --git a/src/Controller/AddressBook/SetDefaultAddress.php b/src/Controller/AddressBook/SetDefaultAddress.php index 0c56e5dda..2f65f09a1 100644 --- a/src/Controller/AddressBook/SetDefaultAddress.php +++ b/src/Controller/AddressBook/SetDefaultAddress.php @@ -36,11 +36,6 @@ final class SetDefaultAddress */ private $validationErrorViewFactory; - /** - * @var TokenStorageInterface - */ - private $tokenStorage; - /** * CreateAddressAction constructor. * @@ -48,20 +43,17 @@ final class SetDefaultAddress * @param CommandBus $bus * @param ValidatorInterface $validator * @param ValidationErrorViewFactoryInterface $validationErrorViewFactory - * @param TokenStorageInterface $tokenStorage */ public function __construct( ViewHandlerInterface $viewHandler, CommandBus $bus, ValidatorInterface $validator, - ValidationErrorViewFactoryInterface $validationErrorViewFactory, - TokenStorageInterface $tokenStorage + ValidationErrorViewFactoryInterface $validationErrorViewFactory ) { $this->viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; - $this->tokenStorage = $tokenStorage; } /** @@ -71,7 +63,7 @@ public function __construct( */ public function __invoke(Request $request) { - $setDefaultAddressRequest = new SetDefaultAddressRequest($request, $this->tokenStorage->getToken()->getUser()); + $setDefaultAddressRequest = new SetDefaultAddressRequest($request); $validationResults = $this->validator->validate($setDefaultAddressRequest); diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index 5bbbf09cc..d962ed07a 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -6,10 +6,12 @@ use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\CustomerInterface; +use Sylius\Component\Core\Model\ShopUser; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\CustomerRepositoryInterface; use Sylius\ShopApiPlugin\Command\SetDefaultAddress; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; final class SetDefaultAddressHandler @@ -24,20 +26,33 @@ final class SetDefaultAddressHandler */ private $addressRepository; - public function __construct(CustomerRepositoryInterface $customerRepository, AddressRepositoryInterface $addressRepository) + /** + * @var TokenStorageInterface + */ + private $tokenStorage; + + public function __construct( + CustomerRepositoryInterface $customerRepository, + AddressRepositoryInterface $addressRepository, + TokenStorageInterface $tokenStorage + ) { $this->customerRepository = $customerRepository; $this->addressRepository = $addressRepository; + $this->tokenStorage = $tokenStorage; } public function handle(SetDefaultAddress $setDefaultAddress): void { /** @var AddressInterface $address */ $address = $this->addressRepository->find($setDefaultAddress->id); - /** @var CustomerInterface $customer */ - $customer = $setDefaultAddress->user->getCustomer(); + /** @var ShopUser */ + $user = $this->tokenStorage->getToken()->getUser(); + + $this->assertCurrentUserIsOwner($address, $user); - $this->assertCurrentUserIsOwner($address, $setDefaultAddress->user); + /** @var CustomerInterface $customer */ + $customer = $user->getCustomer(); $customer->setDefaultAddress($address); $this->customerRepository->add($customer); diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index b4a1a1b49..ac9b9a1b9 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -15,15 +15,9 @@ final class SetDefaultAddressRequest */ private $id; - /** - * @var ShopUserInterface - */ - private $user; - - public function __construct(Request $request, ShopUserInterface $user) + public function __construct(Request $request) { $this->id = $request->attributes->get('id'); - $this->user = $user; } /** @@ -31,6 +25,6 @@ public function __construct(Request $request, ShopUserInterface $user) */ public function getCommand() { - return new SetDefaultAddress($this->id, $this->user); + return new SetDefaultAddress($this->id); } } diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index 35c4b93f0..920f6eabd 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -24,7 +24,6 @@ - - \ No newline at end of file diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index b9b68d636..860fda14f 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -171,6 +171,7 @@ + diff --git a/tests/Request/SetDefaultAddressRequestTest.php b/tests/Request/SetDefaultAddressRequestTest.php index 1c665852a..988938abe 100644 --- a/tests/Request/SetDefaultAddressRequestTest.php +++ b/tests/Request/SetDefaultAddressRequestTest.php @@ -5,13 +5,19 @@ namespace Tests\Sylius\ShopApiPlugin\Request; use PHPUnit\Framework\TestCase; +use Sylius\ShopApiPlugin\Command\SetDefaultAddress; +use Sylius\ShopApiPlugin\Request\SetDefaultAddressRequest; +use Symfony\Component\HttpFoundation\Request; class SetDefaultAddressRequestTest extends TestCase { /** * @test */ - public function it_creates_set_default_addres_command() + public function it_creates_set_default_address_command() { + $setDefaultAddressRequest = new SetDefaultAddressRequest(new Request([], [], ['id' => '1'])); + + $this->assertEquals( $setDefaultAddressRequest->getCommand(), new SetDefaultAddress('1')); } } From 8f1aa838059512e2b476c9d51c2197491ccea686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 30 Oct 2017 16:04:59 +0100 Subject: [PATCH 18/34] [Address-book] apply ecs fixes --- tests/Controller/AddressBookSetDefaultAddressApiTest.php | 2 +- tests/Request/RemoveAddressRequestTest.php | 2 +- tests/Request/SetDefaultAddressRequestTest.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Controller/AddressBookSetDefaultAddressApiTest.php b/tests/Controller/AddressBookSetDefaultAddressApiTest.php index 8accb38a9..10706fe16 100644 --- a/tests/Controller/AddressBookSetDefaultAddressApiTest.php +++ b/tests/Controller/AddressBookSetDefaultAddressApiTest.php @@ -6,11 +6,11 @@ use Lakion\ApiTestCase\JsonApiTestCase; use PHPUnit\Framework\Assert; +use Sylius\Component\Core\Model\ShopUser; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\User\Repository\UserRepositoryInterface; use Symfony\Component\HttpFoundation\Response; -use Sylius\Component\Core\Model\ShopUser; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; class AddressBookSetDefaultAddressApiTest extends JsonApiTestCase diff --git a/tests/Request/RemoveAddressRequestTest.php b/tests/Request/RemoveAddressRequestTest.php index d10eb4b5b..b758e6c09 100644 --- a/tests/Request/RemoveAddressRequestTest.php +++ b/tests/Request/RemoveAddressRequestTest.php @@ -20,4 +20,4 @@ public function it_creates_remove_address_command() $this->assertEquals($removeAddressRequest->getCommand(), new RemoveAddress('1')); } -} \ No newline at end of file +} diff --git a/tests/Request/SetDefaultAddressRequestTest.php b/tests/Request/SetDefaultAddressRequestTest.php index 988938abe..a93878de0 100644 --- a/tests/Request/SetDefaultAddressRequestTest.php +++ b/tests/Request/SetDefaultAddressRequestTest.php @@ -18,6 +18,6 @@ public function it_creates_set_default_address_command() { $setDefaultAddressRequest = new SetDefaultAddressRequest(new Request([], [], ['id' => '1'])); - $this->assertEquals( $setDefaultAddressRequest->getCommand(), new SetDefaultAddress('1')); + $this->assertEquals($setDefaultAddressRequest->getCommand(), new SetDefaultAddress('1')); } } From 45a1202b3a28941134be95a74c4099be038791dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Thu, 2 Nov 2017 11:53:14 +0100 Subject: [PATCH 19/34] [Address-book] add phpspec --- spec/Command/CreateAddressSpec.php | 72 ++++++ spec/Command/RemoveAddressSpec.php | 26 +++ spec/Command/SetDefaultAddressSpec.php | 26 +++ spec/Command/UpdateAddressSpec.php | 84 +++++++ spec/Factory/AddressBookViewFactorySpec.php | 57 +++++ spec/Handler/CreateAddressHandlerSpec.php | 209 +++++++++++++++++ spec/Handler/RemoveAddressHandlerSpec.php | 110 +++++++++ spec/Handler/SetDefaultAddressHandlerSpec.php | 88 +++++++ .../UpdateAddressBookAddressHandlerSpec.php | 220 ++++++++++++++++++ spec/Validator/AddressExistsValidatorSpec.php | 45 ++++ src/Command/RemoveAddress.php | 10 +- src/Command/SetDefaultAddress.php | 12 +- .../AddressBook/CreateAddressAction.php | 1 - .../AddressBook/SetDefaultAddress.php | 1 - src/Handler/CreateAddressHandler.php | 23 +- src/Handler/RemoveAddressHandler.php | 2 +- src/Handler/SetDefaultAddressHandler.php | 5 +- src/Request/SetDefaultAddressRequest.php | 1 - 18 files changed, 959 insertions(+), 33 deletions(-) create mode 100644 spec/Command/CreateAddressSpec.php create mode 100644 spec/Command/RemoveAddressSpec.php create mode 100644 spec/Command/SetDefaultAddressSpec.php create mode 100644 spec/Command/UpdateAddressSpec.php create mode 100644 spec/Factory/AddressBookViewFactorySpec.php create mode 100644 spec/Handler/CreateAddressHandlerSpec.php create mode 100644 spec/Handler/RemoveAddressHandlerSpec.php create mode 100644 spec/Handler/SetDefaultAddressHandlerSpec.php create mode 100644 spec/Handler/UpdateAddressBookAddressHandlerSpec.php create mode 100644 spec/Validator/AddressExistsValidatorSpec.php diff --git a/spec/Command/CreateAddressSpec.php b/spec/Command/CreateAddressSpec.php new file mode 100644 index 000000000..77101f6a2 --- /dev/null +++ b/spec/Command/CreateAddressSpec.php @@ -0,0 +1,72 @@ +beConstructedWith(Address::createFromArray([ + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceName' => 'Greater London', + 'provinceCode' => 'GB-GL', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ])); + } + + function it_has_first_name() + { + $this->firstName()->shouldReturn('Sherlock'); + } + + function it_has_last_name() + { + $this->lastName()->shouldReturn('Holmes'); + } + + function it_has_company() + { + $this->company()->shouldReturn('Sherlock ltd.'); + } + + function it_has_street() + { + $this->street()->shouldReturn('Baker Street 221b'); + } + + function it_has_country_code() + { + $this->countryCode()->shouldReturn('GB'); + } + + function it_has_province_code() + { + $this->provinceCode()->shouldReturn('GB-GL'); + } + + function it_has_city() + { + $this->city()->shouldReturn('London'); + } + + function it_has_postcode() + { + $this->postcode()->shouldReturn('NWB'); + } + + function it_has_phone_number() + { + $this->phoneNumber()->shouldReturn('0912538092'); + } +} diff --git a/spec/Command/RemoveAddressSpec.php b/spec/Command/RemoveAddressSpec.php new file mode 100644 index 000000000..aa33bf4df --- /dev/null +++ b/spec/Command/RemoveAddressSpec.php @@ -0,0 +1,26 @@ +shouldHaveType(RemoveAddress::class); + } + + function let() + { + $this->beConstructedWith('1'); + } + + function it_has_id() + { + $this->id()->shouldReturn('1'); + } +} diff --git a/spec/Command/SetDefaultAddressSpec.php b/spec/Command/SetDefaultAddressSpec.php new file mode 100644 index 000000000..f84602889 --- /dev/null +++ b/spec/Command/SetDefaultAddressSpec.php @@ -0,0 +1,26 @@ +shouldHaveType(SetDefaultAddress::class); + } + + function let() + { + $this->beConstructedWith('ADDRESS_ID'); + } + + function it_has_id() + { + $this->id()->shouldReturn('ADDRESS_ID'); + } +} diff --git a/spec/Command/UpdateAddressSpec.php b/spec/Command/UpdateAddressSpec.php new file mode 100644 index 000000000..93d4dc7bd --- /dev/null +++ b/spec/Command/UpdateAddressSpec.php @@ -0,0 +1,84 @@ +shouldHaveType(UpdateAddress::class); + } + + function let() + { + $this->beConstructedWith(Address::createFromArray([ + 'id' => 'ADDRESS_ID', + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceName' => 'Greater London', + 'provinceCode' => 'GB-GL', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ])); + } + + function it_has_address_id() + { + $this->id()->shouldReturn('ADDRESS_ID'); + } + + function it_has_first_name() + { + $this->firstName()->shouldReturn('Sherlock'); + } + + function it_has_last_name() + { + $this->lastName()->shouldReturn('Holmes'); + } + + function it_has_company() + { + $this->company()->shouldReturn('Sherlock ltd.'); + } + + function it_has_street() + { + $this->street()->shouldReturn('Baker Street 221b'); + } + + function it_has_country_code() + { + $this->countryCode()->shouldReturn('GB'); + } + + function it_has_province_code() + { + $this->provinceCode()->shouldReturn('GB-GL'); + } + + function it_has_city() + { + $this->city()->shouldReturn('London'); + } + + function it_has_postcode() + { + $this->postcode()->shouldReturn('NWB'); + } + + function it_has_phone_number() + { + $this->phoneNumber()->shouldReturn('0912538092'); + } +} diff --git a/spec/Factory/AddressBookViewFactorySpec.php b/spec/Factory/AddressBookViewFactorySpec.php new file mode 100644 index 000000000..6e3fe8b33 --- /dev/null +++ b/spec/Factory/AddressBookViewFactorySpec.php @@ -0,0 +1,57 @@ +beConstructedWith(AddressBookView::class); + } + + function it_is_initializable() + { + $this->shouldHaveType(AddressBookViewFactory::class); + } + + function it_creates_address_book_view(AddressInterface $address, CustomerInterface $customer) + { + $address->getId()->willReturn('ADDRESS_ID'); + $address->getFirstName()->willReturn('Sherlock'); + $address->getLastName()->willReturn('Holmes'); + $address->getCountryCode()->willReturn('GB'); + $address->getCity()->willReturn('London'); + $address->getStreet()->willReturn('Baker Street 221b'); + $address->getPostcode()->willReturn('NMW'); + $address->getProvinceName()->willReturn('Greater London'); + $address->getProvinceCode()->willReturn('GB-GL'); + $address->getPhoneNumber()->willReturn('0912538092'); + $address->getCompany()->willReturn('Sherlock ltd.'); + + $customer->getDefaultAddress()->willReturn($address); + + $addressBookView = new AddressBookView(); + $addressBookView->id = 'ADDRESS_ID'; + $addressBookView->firstName = 'Sherlock'; + $addressBookView->lastName = 'Holmes'; + $addressBookView->countryCode = 'GB'; + $addressBookView->city = 'London'; + $addressBookView->street = 'Baker Street 221b'; + $addressBookView->postcode = 'NMW'; + $addressBookView->provinceName = 'Greater London'; + $addressBookView->provinceCode = 'GB-GL'; + $addressBookView->phoneNumber = '0912538092'; + $addressBookView->company = 'Sherlock ltd.'; + $addressBookView->default = true; + + $this->create($address, $customer)->shouldBeLike($addressBookView); + } +} diff --git a/spec/Handler/CreateAddressHandlerSpec.php b/spec/Handler/CreateAddressHandlerSpec.php new file mode 100644 index 000000000..26bc79b75 --- /dev/null +++ b/spec/Handler/CreateAddressHandlerSpec.php @@ -0,0 +1,209 @@ +beConstructedWith( + $addressRepository, + $countryRepository, + $provinceRepository, + $addressFactory, + $tokenStorage + ); + } + + function it_creates_new_address_for_current_user( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + RepositoryInterface $countryRepository, + CountryInterface $country, + AddressInterface $address, + FactoryInterface $addressFactory + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); + + $addressFactory->createNew()->willReturn($address); + + $address->setFirstName('Sherlock')->shouldBeCalled(); + $address->setLastName('Holmes')->shouldBeCalled(); + $address->setCity('London')->shouldBeCalled(); + $address->setStreet('Baker Street 221b')->shouldBeCalled(); + $address->setCountryCode('GB')->shouldBeCalled(); + $address->setPostcode('NWB')->shouldBeCalled(); + $address->setCompany('Sherlock ltd.')->shouldBeCalled(); + $address->setPhoneNumber('0912538092')->shouldBeCalled(); + + $addressRepository->add($address)->shouldBeCalled(); + + $this->handle(new CreateAddress(Address::createFromArray([ + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'company' => 'Sherlock ltd.', + 'phoneNumber' => '0912538092', + ]))); + } + + function it_creates_new_address_with_province_for_current_user( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + RepositoryInterface $countryRepository, + RepositoryInterface $provinceRepository, + CountryInterface $country, + AddressInterface $address, + ProvinceInterface $province, + FactoryInterface $addressFactory + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); + + $addressFactory->createNew()->willReturn($address); + + $address->setFirstName('Sherlock')->shouldBeCalled(); + $address->setLastName('Holmes')->shouldBeCalled(); + $address->setCity('London')->shouldBeCalled(); + $address->setStreet('Baker Street 221b')->shouldBeCalled(); + $address->setCountryCode('GB')->shouldBeCalled(); + $address->setPostcode('NWB')->shouldBeCalled(); + $address->setProvinceName('Greater London')->shouldBeCalled(); + $address->setCompany('Sherlock ltd.')->shouldBeCalled(); + $address->setPhoneNumber('0912538092')->shouldBeCalled(); + + $provinceRepository->findOneBy(['code' => 'GB-GL'])->willReturn($province); + $province->getCode()->willReturn('GB-GL'); + $province->getName()->willReturn('Greater London'); + + $address->setProvinceCode('GB-GL')->shouldBeCalled(); + $address->setProvinceName('Greater London')->shouldBeCalled(); + + $addressRepository->add($address)->shouldBeCalled(); + + $this->handle(new CreateAddress(Address::createFromArray([ + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceCode' => 'GB-GL', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ]))); + } + + function it_throws_exception_if_country_code_is_invalid( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $countryRepository + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $countryRepository->findOneBy(['code' => 'WRONG_COUNTRY_CODE'])->willReturn(null); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new CreateAddress(Address::createFromArray([ + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'WRONG_COUNTRY_CODE', + 'postcode' => 'NWB', + 'provinceCode' => 'GB-GL', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ]))]); + } + + function it_throws_exception_if_province_code_is_invalid( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + RepositoryInterface $countryRepository, + RepositoryInterface $provinceRepository, + CountryInterface $country, + AddressInterface $address, + ProvinceInterface $province, + FactoryInterface $addressFactory + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); + + $addressFactory->createNew()->willReturn($address); + + $address->setFirstName('Sherlock')->shouldBeCalled(); + $address->setLastName('Holmes')->shouldBeCalled(); + $address->setCity('London')->shouldBeCalled(); + $address->setStreet('Baker Street 221b')->shouldBeCalled(); + $address->setCountryCode('GB')->shouldBeCalled(); + $address->setPostcode('NWB')->shouldBeCalled(); + $address->setProvinceName('Greater London')->shouldBeCalled(); + $address->setCompany('Sherlock ltd.')->shouldBeCalled(); + $address->setPhoneNumber('0912538092')->shouldBeCalled(); + + $provinceRepository->findOneBy(['code' => 'WRONG_PROVINCE_CODE'])->willReturn(null); + + $address->setProvinceCode('WRONG_PROVINCE_CODE')->shouldNotBeCalled(); + $address->setProvinceName('Greater London')->shouldNotBeCalled(); + + $addressRepository->add($address)->shouldNotBeCalled(); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new CreateAddress(Address::createFromArray([ + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceCode' => 'WRONG_PROVINCE_CODE', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ]))]); + } +} diff --git a/spec/Handler/RemoveAddressHandlerSpec.php b/spec/Handler/RemoveAddressHandlerSpec.php new file mode 100644 index 000000000..b010c9865 --- /dev/null +++ b/spec/Handler/RemoveAddressHandlerSpec.php @@ -0,0 +1,110 @@ +beConstructedWith( + $addressRepository, + $orderRepository, + $tokenStorage + ); + } + + function it_removes_address_from_address_book( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + AddressRepository $addressRepository, + OrderRepositoryInterface $orderRepository, + AddressInterface $address + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $customer->getId()->willReturn('USER_ID'); + $shopUser->getId()->willReturn('USER_ID'); + $address->getCustomer()->willReturn($customer); + + $orderRepository->findBy(['billingAddress' => $address])->willReturn([]); + $orderRepository->findBy(['shippingAddress' => $address])->willReturn([]); + + $addressRepository->remove($address)->shouldBeCalled(); + + $this->handle(new RemoveAddress('ADDRESS_ID')); + } + + function it_throws_an_exception_when_deleting_address_associated_with_order( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + AddressRepository $addressRepository, + OrderRepositoryInterface $orderRepository, + AddressInterface $address, + OrderInterface $order + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $customer->getId()->willReturn('USER_ID'); + $shopUser->getId()->willReturn('USER_ID'); + $address->getCustomer()->willReturn($customer); + + $orderRepository->findBy(['billingAddress' => $address])->willReturn($order); + $orderRepository->findBy(['shippingAddress' => $address])->willReturn($order); + + $addressRepository->remove($address)->shouldNotBeCalled(); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID')]); + } + + function it_trows_exception_if_address_does_not_belong_to_current_user( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + AddressRepository $addressRepository, + AddressInterface $address + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $customer->getId()->willReturn('USER_ID_1'); + $shopUser->getId()->willReturn('USER_ID_2'); + $address->getCustomer()->willReturn($customer); + + $addressRepository->remove($address)->shouldNotBeCalled(); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID')]); + } +} diff --git a/spec/Handler/SetDefaultAddressHandlerSpec.php b/spec/Handler/SetDefaultAddressHandlerSpec.php new file mode 100644 index 000000000..829330492 --- /dev/null +++ b/spec/Handler/SetDefaultAddressHandlerSpec.php @@ -0,0 +1,88 @@ +beConstructedWith($customerRepository, $addressRepository, $tokenStorage); + } + + function it_handles_setting_default_address_for_user( + AddressInterface $address, + AddressRepositoryInterface $addressRepository, + TokenStorageInterface $tokenStorage, + ShopUserInterface $user, + Customer $customer, + JWTUserToken $userToken + ) { + $addressRepository->find('ADDRESS_ID')->willReturn($address); + + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($user); + $user->getCustomer()->willReturn($customer); + + $address->getCustomer()->willReturn($customer); + + $customer->getId()->willReturn('USER_ID'); + $user->getId()->willReturn('USER_ID'); + + $customer->setDefaultAddress($address)->shouldBeCalled(); + + $this->handle(new SetDefaultAddress('ADDRESS_ID')); + } + + function it_trows_exception_if_address_does_not_belong_to_current_user( + AddressInterface $address, + AddressRepositoryInterface $addressRepository, + TokenStorageInterface $tokenStorage, + ShopUserInterface $user, + Customer $customer, + JWTUserToken $userToken + ) { + $addressRepository->find('ADDRESS_ID')->willReturn($address); + + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($user); + $user->getCustomer()->willReturn($customer); + + $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID_1'); + $user->getId()->willReturn('USER_ID_2'); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new SetDefaultAddress('ADDRESS_ID')]); + } + + function it_trows_exception_if_address_is_not_associated_with_any_user( + AddressInterface $address, + AddressRepositoryInterface $addressRepository, + TokenStorageInterface $tokenStorage, + ShopUserInterface $user, + JWTUserToken $userToken + ) { + $addressRepository->find('ADDRESS_ID')->willReturn($address); + $address->getCustomer()->willReturn(null); + + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($user); + + $user->getId()->shouldNotBeCalled(); + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new SetDefaultAddress('ADDRESS_ID')]); + } +} diff --git a/spec/Handler/UpdateAddressBookAddressHandlerSpec.php b/spec/Handler/UpdateAddressBookAddressHandlerSpec.php new file mode 100644 index 000000000..a7050fabc --- /dev/null +++ b/spec/Handler/UpdateAddressBookAddressHandlerSpec.php @@ -0,0 +1,220 @@ +beConstructedWith( + $addressRepository, + $countryRepository, + $provinceRepository, + $addressFactory, + $tokenStorage + ); + } + + function it_updates_address( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + RepositoryInterface $countryRepository, + RepositoryInterface $provinceRepository, + ProvinceInterface $province, + CountryInterface $country, + AddressInterface $address + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID'); + $shopUser->getId()->willReturn('USER_ID'); + + $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); + + $address->setFirstName('Sherlock')->shouldBeCalled(); + $address->setLastName('Holmes')->shouldBeCalled(); + $address->setCity('London')->shouldBeCalled(); + $address->setStreet('Baker Street 221b')->shouldBeCalled(); + $address->setCountryCode('GB')->shouldBeCalled(); + $address->setPostcode('NWB')->shouldBeCalled(); + $address->setCompany('Sherlock ltd.')->shouldBeCalled(); + $address->setPhoneNumber('0912538092')->shouldBeCalled(); + + $address->getProvinceCode()->willReturn('GB-AL'); + + $provinceRepository->findOneBy(['code' => 'GB-GL'])->willReturn($province); + $province->getCode()->willReturn('GB-GL'); + $province->getName()->willReturn('Greater London'); + + $address->setProvinceCode('GB-GL')->shouldBeCalled(); + $address->setProvinceName('Greater London')->shouldBeCalled(); + + $addressRepository->add($address)->shouldBeCalled(); + + $this->handle(new UpdateAddress(Address::createFromArray([ + 'id' => 'ADDRESS_ID', + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceCode' => 'GB-GL', + 'company' => 'Sherlock ltd.', + 'phoneNumber' => '0912538092', + ]))); + } + + function it_throws_an_exception_if_current_user_is_not_address_owner( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + AddressInterface $address + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID_1'); + $shopUser->getId()->willReturn('USER_ID_2'); + + $addressRepository->add($address)->shouldNotBeCalled(); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new UpdateAddress(Address::createFromArray([ + 'id' => 'ADDRESS_ID', + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ]))]); + } + + function it_throws_an_exception_if_country_does_not_exists( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + RepositoryInterface $countryRepository, + CountryInterface $country, + AddressInterface $address + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID'); + $shopUser->getId()->willReturn('USER_ID'); + + $countryRepository->findOneBy(['code' => 'GB'])->willReturn(null); + + $addressRepository->add($address)->shouldNotBeCalled(); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new UpdateAddress(Address::createFromArray([ + 'id' => 'ADDRESS_ID', + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceCode' => 'GB-GL', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ]))]); + } + + function it_throws_an_exception_if_province_code_does_not_exists( + TokenStorageInterface $tokenStorage, + JWTUserToken $userToken, + ShopUserInterface $shopUser, + CustomerInterface $customer, + RepositoryInterface $addressRepository, + RepositoryInterface $countryRepository, + RepositoryInterface $provinceRepository, + CountryInterface $country, + AddressInterface $address + ) { + $tokenStorage->getToken()->willReturn($userToken); + $userToken->getUser()->willReturn($shopUser); + $shopUser->getCustomer()->willReturn($customer); + + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID'); + $shopUser->getId()->willReturn('USER_ID'); + + $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); + + $address->setFirstName('Sherlock')->shouldBeCalled(); + $address->setLastName('Holmes')->shouldBeCalled(); + $address->setCity('London')->shouldBeCalled(); + $address->setStreet('Baker Street 221b')->shouldBeCalled(); + $address->setCountryCode('GB')->shouldBeCalled(); + $address->setPostcode('NWB')->shouldBeCalled(); + $address->setCompany('Sherlock ltd.')->shouldBeCalled(); + $address->setPhoneNumber('0912538092')->shouldBeCalled(); + + $address->getProvinceCode()->willReturn('GB-AL'); + + $provinceRepository->findOneBy(['code' => 'WRONG_PROVINCE_CODE'])->willReturn(null); + + $address->setProvinceCode(null)->shouldNotBeCalled(); + $address->setProvinceName(null)->shouldNotBeCalled(); + $addressRepository->add($address)->shouldNotBeCalled(); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new UpdateAddress(Address::createFromArray([ + 'id' => 'ADDRESS_ID', + 'firstName' => 'Sherlock', + 'lastName' => 'Holmes', + 'city' => 'London', + 'street' => 'Baker Street 221b', + 'countryCode' => 'GB', + 'postcode' => 'NWB', + 'provinceCode' => 'WRONG_PROVINCE_CODE', + 'phoneNumber' => '0912538092', + 'company' => 'Sherlock ltd.', + ]))]); + } +} diff --git a/spec/Validator/AddressExistsValidatorSpec.php b/spec/Validator/AddressExistsValidatorSpec.php new file mode 100644 index 000000000..6bfd9b953 --- /dev/null +++ b/spec/Validator/AddressExistsValidatorSpec.php @@ -0,0 +1,45 @@ +beConstructedWith($addressRepository); + + $this->initialize($executionContext); + } + + function it_does_not_add_constraint_if_address_exists( + AddressInterface $address, + AddressRepositoryInterface $addressRepository, + ExecutionContextInterface $executionContext + ) { + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $executionContext->addViolation(Argument::any(), Argument::any())->shouldNotBeCalled(); + + $this->validate('ADDRESS_ID', new AddressExists()); + } + + function it_adds_constraint_if_address_does_not_exits_exists( + AddressRepositoryInterface $addressRepository, + ExecutionContextInterface $executionContext + ) { + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn(null); + + $executionContext->addViolation('sylius.shop_api.address.not_exists')->shouldBeCalled(); + + $this->validate('ADDRESS_ID', new AddressExists()); + } +} diff --git a/src/Command/RemoveAddress.php b/src/Command/RemoveAddress.php index 97f883973..ba37ea284 100644 --- a/src/Command/RemoveAddress.php +++ b/src/Command/RemoveAddress.php @@ -9,7 +9,7 @@ class RemoveAddress /** * @var mixed */ - public $id; + private $id; /** * @param $id @@ -18,4 +18,12 @@ public function __construct($id) { $this->id = $id; } + + /** + * @return mixed + */ + public function id() + { + return $this->id; + } } diff --git a/src/Command/SetDefaultAddress.php b/src/Command/SetDefaultAddress.php index 9a4f91317..bb7837ff5 100644 --- a/src/Command/SetDefaultAddress.php +++ b/src/Command/SetDefaultAddress.php @@ -4,17 +4,23 @@ namespace Sylius\ShopApiPlugin\Command; -use Sylius\Component\Core\Model\ShopUserInterface; - class SetDefaultAddress { /** * @var mixed */ - public $id; + private $id; public function __construct($id) { $this->id = $id; } + + /** + * @return mixed + */ + public function id() + { + return $this->id; + } } diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index 201be0701..4cbf9a2f4 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -76,4 +76,3 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } } - diff --git a/src/Controller/AddressBook/SetDefaultAddress.php b/src/Controller/AddressBook/SetDefaultAddress.php index 2f65f09a1..25511d9e6 100644 --- a/src/Controller/AddressBook/SetDefaultAddress.php +++ b/src/Controller/AddressBook/SetDefaultAddress.php @@ -11,7 +11,6 @@ use Sylius\ShopApiPlugin\Request\SetDefaultAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; final class SetDefaultAddress diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index 47ca4dc32..bd1218b13 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -4,9 +4,7 @@ namespace Sylius\ShopApiPlugin\Handler; -use Sylius\Component\Addressing\Model\ProvinceInterface; use Sylius\Component\Core\Model\AddressInterface; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; @@ -68,7 +66,6 @@ public function handle(CreateAddress $command): void $user = $this->tokenStorage->getToken()->getUser(); $customer = $user->getCustomer(); - $this->assertShopUserExists($user); $this->assertCountryExists($command->countryCode()); /** @var AddressInterface $address */ @@ -83,7 +80,7 @@ public function handle(CreateAddress $command): void $address->setPhoneNumber($command->phoneNumber()); if (null !== $command->provinceCode()) { - $province = $this->getProvince($command->provinceCode()); + $province = $this->provinceRepository->findOneBy(['code' => $command->provinceCode()]); $this->assertProvinceExists($province); $address->setProvinceCode($province->getCode()); $address->setProvinceName($province->getName()); @@ -108,22 +105,4 @@ private function assertProvinceExists($province): void { Assert::notNull($province, 'Province does not exist.'); } - - /** - * @param string $provinceCode - * - * @return ProvinceInterface|object - */ - private function getProvince(string $provinceCode) - { - return $this->provinceRepository->findOneBy(['code' => $provinceCode]); - } - - /** - * @param $user - */ - private function assertShopUserExists($user) - { - Assert::isInstanceOf($user, ShopUserInterface::class, 'Logged in user does not exist'); - } } diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 34cfeebaf..4bdcd8c43 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -43,7 +43,7 @@ public function handle(RemoveAddress $removeAddress) $user = $this->tokenStorage->getToken()->getUser(); /** @var AddressInterface $address */ - $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id]); + $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id()]); $this->assertCurrentUserIsOwner($address, $user); $this->assertOrderWithAddressNotExists($address); diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index d962ed07a..1bf5cb440 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -35,8 +35,7 @@ public function __construct( CustomerRepositoryInterface $customerRepository, AddressRepositoryInterface $addressRepository, TokenStorageInterface $tokenStorage - ) - { + ) { $this->customerRepository = $customerRepository; $this->addressRepository = $addressRepository; $this->tokenStorage = $tokenStorage; @@ -45,7 +44,7 @@ public function __construct( public function handle(SetDefaultAddress $setDefaultAddress): void { /** @var AddressInterface $address */ - $address = $this->addressRepository->find($setDefaultAddress->id); + $address = $this->addressRepository->find($setDefaultAddress->id()); /** @var ShopUser */ $user = $this->tokenStorage->getToken()->getUser(); diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index ac9b9a1b9..46da25fff 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -4,7 +4,6 @@ namespace Sylius\ShopApiPlugin\Request; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\ShopApiPlugin\Command\SetDefaultAddress; use Symfony\Component\HttpFoundation\Request; From 2e57ef3b0ca0556d92a1bf9e448b857f646dc178 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Thu, 2 Nov 2017 12:21:35 +0100 Subject: [PATCH 20/34] [Address-book] add validation labels, and change address constructor parameters order --- src/Model/Address.php | 10 +-- .../config/validation/AddressModelRequest.xml | 2 +- .../validation/CreateAddressRequest.xml | 66 ------------------- .../validation/RemoveAddressRequest.xml | 2 +- .../validation/SetDefaultAddressRequest.xml | 2 +- src/Resources/translations/validators.en.yml | 5 ++ 6 files changed, 13 insertions(+), 74 deletions(-) delete mode 100644 src/Resources/config/validation/CreateAddressRequest.xml diff --git a/src/Model/Address.php b/src/Model/Address.php index 7de038273..e068a0adc 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -65,38 +65,38 @@ final class Address private $phoneNumber; /** - * @param null $id * @param string $firstName * @param string $lastName * @param string $city * @param string $street * @param string $countryCode * @param string $postcode + * @param null $id * @param string $provinceName * @param null $provinceCode * @param null $company * @param null $phoneNumber */ private function __construct( - $id = null, $firstName, $lastName, $city, $street, $countryCode, $postcode, + $id = null, $provinceName = null, $provinceCode = null, $phoneNumber = null, $company = null ) { - $this->id = $id; $this->firstName = $firstName; $this->lastName = $lastName; $this->city = $city; $this->street = $street; $this->countryCode = $countryCode; $this->postcode = $postcode; + $this->id = $id; $this->provinceName = $provinceName; $this->provinceCode = $provinceCode; $this->phoneNumber = $phoneNumber; @@ -118,13 +118,13 @@ public static function createFromArray(array $address) Assert::keyExists($address, 'postcode'); return new self( - $address['id'] ?? null, $address['firstName'], $address['lastName'], $address['city'], $address['street'], $address['countryCode'], $address['postcode'], + $address['id'] ?? null, $address['provinceName'] ?? null, $address['provinceCode'] ?? null, $address['phoneNumber'] ?? null, @@ -140,13 +140,13 @@ public static function createFromArray(array $address) public static function createFromRequest(Request $request) { return new self( - $request->attributes->get('id') ?? $request->request->get('id'), $request->request->get('firstName'), $request->request->get('lastName'), $request->request->get('city'), $request->request->get('street'), $request->request->get('countryCode'), $request->request->get('postcode'), + $request->attributes->get('id') ?? $request->request->get('id'), $request->request->get('provinceName'), $request->request->get('provinceCode'), $request->request->get('phoneNumber'), diff --git a/src/Resources/config/validation/AddressModelRequest.xml b/src/Resources/config/validation/AddressModelRequest.xml index 6b0ab9b3c..036e62c8c 100644 --- a/src/Resources/config/validation/AddressModelRequest.xml +++ b/src/Resources/config/validation/AddressModelRequest.xml @@ -5,7 +5,7 @@ - + diff --git a/src/Resources/config/validation/CreateAddressRequest.xml b/src/Resources/config/validation/CreateAddressRequest.xml deleted file mode 100644 index 39e0fc3a9..000000000 --- a/src/Resources/config/validation/CreateAddressRequest.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Resources/config/validation/RemoveAddressRequest.xml b/src/Resources/config/validation/RemoveAddressRequest.xml index 068455655..aeac15c10 100644 --- a/src/Resources/config/validation/RemoveAddressRequest.xml +++ b/src/Resources/config/validation/RemoveAddressRequest.xml @@ -4,7 +4,7 @@ - + diff --git a/src/Resources/config/validation/SetDefaultAddressRequest.xml b/src/Resources/config/validation/SetDefaultAddressRequest.xml index a877897d0..b579e772c 100644 --- a/src/Resources/config/validation/SetDefaultAddressRequest.xml +++ b/src/Resources/config/validation/SetDefaultAddressRequest.xml @@ -4,7 +4,7 @@ - + diff --git a/src/Resources/translations/validators.en.yml b/src/Resources/translations/validators.en.yml index 15426f5b1..959df4806 100644 --- a/src/Resources/translations/validators.en.yml +++ b/src/Resources/translations/validators.en.yml @@ -12,3 +12,8 @@ sylius: not_blank: Please enter your first name. last_name: not_blank: Please enter your last name. + address_id: + not_null: Please provide address id + address: + not_exists: Address doesn't exist + From 528c8ad9bed40dfb22d5d7910fa459f0477d6004 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Thu, 2 Nov 2017 13:13:59 +0100 Subject: [PATCH 21/34] [Address-book] returned old path for sql --- tests/Application/app/config/config.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/Application/app/config/config.yml b/tests/Application/app/config/config.yml index ad4f4c6e0..8d6f145a0 100644 --- a/tests/Application/app/config/config.yml +++ b/tests/Application/app/config/config.yml @@ -36,8 +36,7 @@ framework: doctrine: dbal: driver: "pdo_sqlite" -# path: "%kernel.cache_dir%/db.sql" - path: "/run/shm/sylius/cache/test/db.sql" + path: "%kernel.cache_dir%/db.sql" charset: UTF8 fos_rest: From 2df80ea401a47c8f5ade5c6ea585b97cf4db0ab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 3 Nov 2017 11:57:30 +0100 Subject: [PATCH 22/34] [Address-book] add final to all phpunit tests --- tests/Controller/AddressBookCreateAddressApiTest.php | 2 +- tests/Controller/AddressBookRemoveAddressApiTest.php | 2 +- tests/Controller/AddressBookSetDefaultAddressApiTest.php | 2 +- tests/Controller/AddressBookShowApiTest.php | 2 +- tests/Controller/AddressBookUpdateAddressApiTest.php | 2 +- tests/Request/RemoveAddressRequestTest.php | 2 +- tests/Request/SetDefaultAddressRequestTest.php | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Controller/AddressBookCreateAddressApiTest.php b/tests/Controller/AddressBookCreateAddressApiTest.php index 0731a2dcf..31164be58 100644 --- a/tests/Controller/AddressBookCreateAddressApiTest.php +++ b/tests/Controller/AddressBookCreateAddressApiTest.php @@ -13,7 +13,7 @@ use Symfony\Component\HttpFoundation\Response; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; -class AddressBookCreateAddressApiTest extends JsonApiTestCase +final class AddressBookCreateAddressApiTest extends JsonApiTestCase { use ShopUserLoginTrait; diff --git a/tests/Controller/AddressBookRemoveAddressApiTest.php b/tests/Controller/AddressBookRemoveAddressApiTest.php index 5cf5247cd..d20a8d87b 100644 --- a/tests/Controller/AddressBookRemoveAddressApiTest.php +++ b/tests/Controller/AddressBookRemoveAddressApiTest.php @@ -11,7 +11,7 @@ use Symfony\Component\HttpFoundation\Response; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; -class AddressBookRemoveAddressApiTest extends JsonApiTestCase +final class AddressBookRemoveAddressApiTest extends JsonApiTestCase { use ShopUserLoginTrait; diff --git a/tests/Controller/AddressBookSetDefaultAddressApiTest.php b/tests/Controller/AddressBookSetDefaultAddressApiTest.php index 10706fe16..f7abe0738 100644 --- a/tests/Controller/AddressBookSetDefaultAddressApiTest.php +++ b/tests/Controller/AddressBookSetDefaultAddressApiTest.php @@ -13,7 +13,7 @@ use Symfony\Component\HttpFoundation\Response; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; -class AddressBookSetDefaultAddressApiTest extends JsonApiTestCase +final class AddressBookSetDefaultAddressApiTest extends JsonApiTestCase { use ShopUserLoginTrait; diff --git a/tests/Controller/AddressBookShowApiTest.php b/tests/Controller/AddressBookShowApiTest.php index 2045e1d51..4bc262ef8 100644 --- a/tests/Controller/AddressBookShowApiTest.php +++ b/tests/Controller/AddressBookShowApiTest.php @@ -8,7 +8,7 @@ use Symfony\Component\HttpFoundation\Response; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; -class AddressBookShowApiTest extends JsonApiTestCase +final class AddressBookShowApiTest extends JsonApiTestCase { use ShopUserLoginTrait; diff --git a/tests/Controller/AddressBookUpdateAddressApiTest.php b/tests/Controller/AddressBookUpdateAddressApiTest.php index cf7765a8e..532d617ab 100644 --- a/tests/Controller/AddressBookUpdateAddressApiTest.php +++ b/tests/Controller/AddressBookUpdateAddressApiTest.php @@ -11,7 +11,7 @@ use Symfony\Component\HttpFoundation\Response; use Tests\Sylius\ShopApiPlugin\Controller\Utils\ShopUserLoginTrait; -class AddressBookUpdateAddressApiTest extends JsonApiTestCase +final class AddressBookUpdateAddressApiTest extends JsonApiTestCase { use ShopUserLoginTrait; diff --git a/tests/Request/RemoveAddressRequestTest.php b/tests/Request/RemoveAddressRequestTest.php index b758e6c09..c27b1394a 100644 --- a/tests/Request/RemoveAddressRequestTest.php +++ b/tests/Request/RemoveAddressRequestTest.php @@ -9,7 +9,7 @@ use Sylius\ShopApiPlugin\Request\RemoveAddressRequest; use Symfony\Component\HttpFoundation\Request; -class RemoveAddressRequestTest extends TestCase +final class RemoveAddressRequestTest extends TestCase { /** * @test diff --git a/tests/Request/SetDefaultAddressRequestTest.php b/tests/Request/SetDefaultAddressRequestTest.php index a93878de0..8a2e6271d 100644 --- a/tests/Request/SetDefaultAddressRequestTest.php +++ b/tests/Request/SetDefaultAddressRequestTest.php @@ -9,7 +9,7 @@ use Sylius\ShopApiPlugin\Request\SetDefaultAddressRequest; use Symfony\Component\HttpFoundation\Request; -class SetDefaultAddressRequestTest extends TestCase +final class SetDefaultAddressRequestTest extends TestCase { /** * @test From b95e3f7260be900d5f7f68a4eeb16dfb12f7526d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 3 Nov 2017 13:07:18 +0100 Subject: [PATCH 23/34] [Address-book] add final classes and empty lines at the end of the file --- spec/Command/UpdateAddressSpec.php | 2 +- spec/Factory/AddressBookViewFactorySpec.php | 2 +- src/Command/CreateAddress.php | 2 -- src/Command/SetDefaultAddress.php | 3 +++ src/Command/UpdateAddress.php | 2 -- src/Controller/AddressBook/CreateAddressAction.php | 2 -- src/Controller/AddressBook/SetDefaultAddress.php | 2 -- src/Handler/RemoveAddressHandler.php | 5 +++++ src/Handler/SetDefaultAddressHandler.php | 5 +++++ src/Handler/UpdateAddressBookAddressHandler.php | 2 -- src/Resources/config/routing/address_book.yml | 1 - src/Resources/config/services/actions/address_book.xml | 2 +- src/Resources/config/validation/SetDefaultAddressRequest.xml | 1 - src/Resources/translations/validators.en.yml | 1 - .../Expected/address_book/show_address_book_response.json | 2 +- tests/Responses/Expected/address_book/update_address.json | 2 +- .../validation_create_address_book_response.json | 2 +- ...tion_create_address_book_with_wrong_country_response.json | 2 +- ...ion_create_address_book_with_wrong_province_response.json | 2 +- 19 files changed, 21 insertions(+), 21 deletions(-) diff --git a/spec/Command/UpdateAddressSpec.php b/spec/Command/UpdateAddressSpec.php index 93d4dc7bd..bfa6110b0 100644 --- a/spec/Command/UpdateAddressSpec.php +++ b/spec/Command/UpdateAddressSpec.php @@ -8,7 +8,7 @@ use Sylius\ShopApiPlugin\Command\UpdateAddress; use Sylius\ShopApiPlugin\Model\Address; -class UpdateAddressSpec extends ObjectBehavior +final class UpdateAddressSpec extends ObjectBehavior { function it_is_initializable() { diff --git a/spec/Factory/AddressBookViewFactorySpec.php b/spec/Factory/AddressBookViewFactorySpec.php index 6e3fe8b33..90bd5631b 100644 --- a/spec/Factory/AddressBookViewFactorySpec.php +++ b/spec/Factory/AddressBookViewFactorySpec.php @@ -10,7 +10,7 @@ use Sylius\ShopApiPlugin\Factory\AddressBookViewFactory; use Sylius\ShopApiPlugin\View\AddressBookView; -class AddressBookViewFactorySpec extends ObjectBehavior +final class AddressBookViewFactorySpec extends ObjectBehavior { function let() { diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index 3088f1a1c..d27afd642 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -14,8 +14,6 @@ final class CreateAddress private $address; /** - * CreateAddress constructor. - * * @param Address $address */ public function __construct(Address $address) diff --git a/src/Command/SetDefaultAddress.php b/src/Command/SetDefaultAddress.php index bb7837ff5..ed05af1a2 100644 --- a/src/Command/SetDefaultAddress.php +++ b/src/Command/SetDefaultAddress.php @@ -11,6 +11,9 @@ class SetDefaultAddress */ private $id; + /** + * @param $id + */ public function __construct($id) { $this->id = $id; diff --git a/src/Command/UpdateAddress.php b/src/Command/UpdateAddress.php index c6e846740..27dd56320 100644 --- a/src/Command/UpdateAddress.php +++ b/src/Command/UpdateAddress.php @@ -14,8 +14,6 @@ final class UpdateAddress private $address; /** - * CreateAddress constructor. - * * @param Address $address */ public function __construct(Address $address) diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index 4cbf9a2f4..9ea210910 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -37,8 +37,6 @@ final class CreateAddressAction private $validationErrorViewFactory; /** - * CreateAddressAction constructor. - * * @param ViewHandlerInterface $viewHandler * @param CommandBus $bus * @param ValidatorInterface $validator diff --git a/src/Controller/AddressBook/SetDefaultAddress.php b/src/Controller/AddressBook/SetDefaultAddress.php index 25511d9e6..a35e5d6c7 100644 --- a/src/Controller/AddressBook/SetDefaultAddress.php +++ b/src/Controller/AddressBook/SetDefaultAddress.php @@ -36,8 +36,6 @@ final class SetDefaultAddress private $validationErrorViewFactory; /** - * CreateAddressAction constructor. - * * @param ViewHandlerInterface $viewHandler * @param CommandBus $bus * @param ValidatorInterface $validator diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 4bdcd8c43..24e56656a 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -30,6 +30,11 @@ final class RemoveAddressHandler */ private $tokenStorage; + /** + * @param AddressRepositoryInterface $addressRepository + * @param OrderRepositoryInterface $orderRepository + * @param TokenStorageInterface $tokenStorage + */ public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, TokenStorageInterface $tokenStorage) { $this->addressRepository = $addressRepository; diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index 1bf5cb440..b15be7645 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -31,6 +31,11 @@ final class SetDefaultAddressHandler */ private $tokenStorage; + /** + * @param CustomerRepositoryInterface $customerRepository + * @param AddressRepositoryInterface $addressRepository + * @param TokenStorageInterface $tokenStorage + */ public function __construct( CustomerRepositoryInterface $customerRepository, AddressRepositoryInterface $addressRepository, diff --git a/src/Handler/UpdateAddressBookAddressHandler.php b/src/Handler/UpdateAddressBookAddressHandler.php index 75426ff42..100d60dcd 100644 --- a/src/Handler/UpdateAddressBookAddressHandler.php +++ b/src/Handler/UpdateAddressBookAddressHandler.php @@ -40,8 +40,6 @@ final class UpdateAddressBookAddressHandler private $tokenStorage; /** - * CreateAddressHandler constructor. - * * @param RepositoryInterface $addressRepository * @param RepositoryInterface $countryRepository * @param RepositoryInterface $provinceRepository diff --git a/src/Resources/config/routing/address_book.yml b/src/Resources/config/routing/address_book.yml index d72685072..8a28c6a83 100644 --- a/src/Resources/config/routing/address_book.yml +++ b/src/Resources/config/routing/address_book.yml @@ -27,4 +27,3 @@ sylius_shop_update_address_book_entry: methods: [PUT] defaults: _controller: sylius.shop_api_plugin.controller.address_book.update_address_action - diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index 920f6eabd..96406f50b 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -45,4 +45,4 @@ - \ No newline at end of file + diff --git a/src/Resources/config/validation/SetDefaultAddressRequest.xml b/src/Resources/config/validation/SetDefaultAddressRequest.xml index b579e772c..413a771b5 100644 --- a/src/Resources/config/validation/SetDefaultAddressRequest.xml +++ b/src/Resources/config/validation/SetDefaultAddressRequest.xml @@ -10,4 +10,3 @@ - diff --git a/src/Resources/translations/validators.en.yml b/src/Resources/translations/validators.en.yml index 959df4806..d71085436 100644 --- a/src/Resources/translations/validators.en.yml +++ b/src/Resources/translations/validators.en.yml @@ -16,4 +16,3 @@ sylius: not_null: Please provide address id address: not_exists: Address doesn't exist - diff --git a/tests/Responses/Expected/address_book/show_address_book_response.json b/tests/Responses/Expected/address_book/show_address_book_response.json index 97352b594..be53786fa 100644 --- a/tests/Responses/Expected/address_book/show_address_book_response.json +++ b/tests/Responses/Expected/address_book/show_address_book_response.json @@ -38,4 +38,4 @@ "phoneNumber": "349713", "default": false } -] \ No newline at end of file +] diff --git a/tests/Responses/Expected/address_book/update_address.json b/tests/Responses/Expected/address_book/update_address.json index e7cad51cd..bdae1442d 100644 --- a/tests/Responses/Expected/address_book/update_address.json +++ b/tests/Responses/Expected/address_book/update_address.json @@ -11,4 +11,4 @@ "company": "Locastic", "phoneNumber": "0918972132", "default": false -} \ No newline at end of file +} diff --git a/tests/Responses/Expected/address_book/validation_create_address_book_response.json b/tests/Responses/Expected/address_book/validation_create_address_book_response.json index 0843112fb..230dfb3c8 100644 --- a/tests/Responses/Expected/address_book/validation_create_address_book_response.json +++ b/tests/Responses/Expected/address_book/validation_create_address_book_response.json @@ -21,4 +21,4 @@ "@string@" ] } -} \ No newline at end of file +} diff --git a/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_country_response.json b/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_country_response.json index d58f1ba52..3bcd9e43a 100644 --- a/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_country_response.json +++ b/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_country_response.json @@ -1,4 +1,4 @@ { "code": 500, "message": "Country does not exist." -} \ No newline at end of file +} diff --git a/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_province_response.json b/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_province_response.json index ae1541867..0505a0e26 100644 --- a/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_province_response.json +++ b/tests/Responses/Expected/address_book/validation_create_address_book_with_wrong_province_response.json @@ -1,4 +1,4 @@ { "code": 500, "message": "Province does not exist." -} \ No newline at end of file +} From 8bdec064b61f4cacf5a162f368500485fd938b66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 3 Nov 2017 13:08:06 +0100 Subject: [PATCH 24/34] [Address-book] Checking province refactored --- src/Handler/CreateAddressHandler.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index bd1218b13..4021a167e 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -4,6 +4,7 @@ namespace Sylius\ShopApiPlugin\Handler; +use Sylius\Component\Addressing\Model\ProvinceInterface; use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; @@ -39,8 +40,6 @@ final class CreateAddressHandler private $tokenStorage; /** - * CreateAddressHandler constructor. - * * @param RepositoryInterface $addressRepository * @param RepositoryInterface $countryRepository * @param RepositoryInterface $provinceRepository @@ -80,8 +79,7 @@ public function handle(CreateAddress $command): void $address->setPhoneNumber($command->phoneNumber()); if (null !== $command->provinceCode()) { - $province = $this->provinceRepository->findOneBy(['code' => $command->provinceCode()]); - $this->assertProvinceExists($province); + $province = $this->checkProvinceExists($command->provinceCode()); $address->setProvinceCode($province->getCode()); $address->setProvinceName($province->getName()); } @@ -99,10 +97,16 @@ private function assertCountryExists(string $countryCode): void } /** - * @param $province + * @param string $provinceCode + * @return ProvinceInterface */ - private function assertProvinceExists($province): void + private function checkProvinceExists(string $provinceCode): ProvinceInterface { + /** @var ProvinceInterface $province */ + $province = $this->provinceRepository->findOneBy(['code' => $provinceCode]); + Assert::notNull($province, 'Province does not exist.'); + + return $province; } } From 151b5df0347db9b68a449d4d6ff2b0b9cd02c6d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 3 Nov 2017 13:11:00 +0100 Subject: [PATCH 25/34] [Address-book] add return type --- src/Request/RemoveAddressRequest.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php index 052a1e3fe..39c5bf625 100644 --- a/src/Request/RemoveAddressRequest.php +++ b/src/Request/RemoveAddressRequest.php @@ -14,11 +14,17 @@ final class RemoveAddressRequest */ private $id; + /** + * @param Request $request + */ public function __construct(Request $request) { $this->id = $request->attributes->get('id'); } + /** + * @return RemoveAddress + */ public function getCommand() { return new RemoveAddress($this->id); From e8d2294ae858d76ca4bd2879759efe6f96b09bca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 3 Nov 2017 13:42:36 +0100 Subject: [PATCH 26/34] [Address-book] changed expected address model parameters types --- src/Model/Address.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Model/Address.php b/src/Model/Address.php index e068a0adc..478151a11 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -71,11 +71,11 @@ final class Address * @param string $street * @param string $countryCode * @param string $postcode - * @param null $id + * @param string $id * @param string $provinceName - * @param null $provinceCode - * @param null $company - * @param null $phoneNumber + * @param string $provinceCode + * @param string $company + * @param string $phoneNumber */ private function __construct( $firstName, From 1a0fc9bb4b301a1c7a192ed7eec6cf8ec54f9b58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 6 Nov 2017 09:38:05 +0100 Subject: [PATCH 27/34] [Address-book] Refactor create address --- spec/Command/CreateAddressSpec.php | 7 ++- spec/Handler/CreateAddressHandlerSpec.php | 57 ++++++------------- src/Command/CreateAddress.php | 17 +++++- .../AddressBook/CreateAddressAction.php | 19 ++++++- src/Handler/CreateAddressHandler.php | 25 +++++--- src/Model/Address.php | 18 ------ src/Request/RemoveAddressRequest.php | 8 +-- src/Request/SetDefaultAddressRequest.php | 5 +- .../config/services/actions/address_book.xml | 1 + src/Resources/config/services/handlers.xml | 2 +- .../config/validation/AddressModelRequest.xml | 30 ---------- tests/Application/app/config/config.yml | 3 +- 12 files changed, 77 insertions(+), 115 deletions(-) diff --git a/spec/Command/CreateAddressSpec.php b/spec/Command/CreateAddressSpec.php index 77101f6a2..297063afe 100644 --- a/spec/Command/CreateAddressSpec.php +++ b/spec/Command/CreateAddressSpec.php @@ -22,7 +22,7 @@ function let() 'provinceCode' => 'GB-GL', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ])); + ]), 'user@email.com'); } function it_has_first_name() @@ -69,4 +69,9 @@ function it_has_phone_number() { $this->phoneNumber()->shouldReturn('0912538092'); } + + function it_has_user_email() + { + $this->userEmail()->shouldReturn('user@email.com'); + } } diff --git a/spec/Handler/CreateAddressHandlerSpec.php b/spec/Handler/CreateAddressHandlerSpec.php index 26bc79b75..a86e92432 100644 --- a/spec/Handler/CreateAddressHandlerSpec.php +++ b/spec/Handler/CreateAddressHandlerSpec.php @@ -4,18 +4,15 @@ namespace spec\Sylius\ShopApiPlugin\Handler; -use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use PhpSpec\ObjectBehavior; use Sylius\Component\Addressing\Model\CountryInterface; use Sylius\Component\Addressing\Model\ProvinceInterface; use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\CustomerInterface; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; use Sylius\ShopApiPlugin\Model\Address; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; final class CreateAddressHandlerSpec extends ObjectBehavior { @@ -23,33 +20,28 @@ function let( RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, - FactoryInterface $addressFactory, - TokenStorageInterface $tokenStorage + RepositoryInterface $customerRepository, + FactoryInterface $addressFactory ) { $this->beConstructedWith( $addressRepository, $countryRepository, $provinceRepository, - $addressFactory, - $tokenStorage + $customerRepository, + $addressFactory ); } function it_creates_new_address_for_current_user( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, - ShopUserInterface $shopUser, CustomerInterface $customer, RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, + RepositoryInterface $customerRepository, CountryInterface $country, AddressInterface $address, FactoryInterface $addressFactory ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $customerRepository->findOneBy(['email' => 'user@email.com'])->willReturn($customer); $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); $addressFactory->createNew()->willReturn($address); @@ -63,6 +55,7 @@ function it_creates_new_address_for_current_user( $address->setCompany('Sherlock ltd.')->shouldBeCalled(); $address->setPhoneNumber('0912538092')->shouldBeCalled(); + $customer->addAddress($address)->shouldBeCalled(); $addressRepository->add($address)->shouldBeCalled(); $this->handle(new CreateAddress(Address::createFromArray([ @@ -74,26 +67,21 @@ function it_creates_new_address_for_current_user( 'postcode' => 'NWB', 'company' => 'Sherlock ltd.', 'phoneNumber' => '0912538092', - ]))); + ]), 'user@email.com')); } function it_creates_new_address_with_province_for_current_user( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, - ShopUserInterface $shopUser, CustomerInterface $customer, RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, + RepositoryInterface $customerRepository, CountryInterface $country, AddressInterface $address, ProvinceInterface $province, FactoryInterface $addressFactory ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $customerRepository->findOneBy(['email' => 'user@email.com'])->willReturn($customer); $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); $addressFactory->createNew()->willReturn($address); @@ -127,20 +115,15 @@ function it_creates_new_address_with_province_for_current_user( 'provinceCode' => 'GB-GL', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ]))); + ]), 'user@email.com')); } function it_throws_exception_if_country_code_is_invalid( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, - ShopUserInterface $shopUser, + RepositoryInterface $customerRepository, CustomerInterface $customer, RepositoryInterface $countryRepository ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $customerRepository->findOneBy(['email' => 'jure@locastic.com'])->willReturn($customer); $countryRepository->findOneBy(['code' => 'WRONG_COUNTRY_CODE'])->willReturn(null); $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new CreateAddress(Address::createFromArray([ @@ -153,26 +136,20 @@ function it_throws_exception_if_country_code_is_invalid( 'provinceCode' => 'GB-GL', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ]))]); + ]), 'jure@locastic.com')]); } function it_throws_exception_if_province_code_is_invalid( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, - ShopUserInterface $shopUser, + RepositoryInterface $customerRepository, CustomerInterface $customer, RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, CountryInterface $country, AddressInterface $address, - ProvinceInterface $province, FactoryInterface $addressFactory ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $customerRepository->findOneBy(['email' => 'user@email.com'])->willReturn($customer); $countryRepository->findOneBy(['code' => 'GB'])->willReturn($country); $addressFactory->createNew()->willReturn($address); @@ -204,6 +181,6 @@ function it_throws_exception_if_province_code_is_invalid( 'provinceCode' => 'WRONG_PROVINCE_CODE', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ]))]); + ]), 'user@email.com')]); } } diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index d27afd642..9236e0d49 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -13,12 +13,19 @@ final class CreateAddress */ private $address; + /** + * @var string + */ + private $userEmail; + /** * @param Address $address + * @param string $userEmail */ - public function __construct(Address $address) + public function __construct(Address $address, string $userEmail) { $this->address = $address; + $this->userEmail = $userEmail; } /** @@ -92,4 +99,12 @@ public function phoneNumber(): ?string { return $this->address->phoneNumber(); } + + /** + * @return null|string + */ + public function userEmail(): ?string + { + return $this->userEmail; + } } diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index 9ea210910..909b83cac 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -7,11 +7,13 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; +use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; use Sylius\ShopApiPlugin\Model\Address; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Validator\Validator\ValidatorInterface; final class CreateAddressAction @@ -36,22 +38,30 @@ final class CreateAddressAction */ private $validationErrorViewFactory; + /** + * @var TokenStorage + */ + private $tokenStorage; + /** * @param ViewHandlerInterface $viewHandler * @param CommandBus $bus * @param ValidatorInterface $validator * @param ValidationErrorViewFactoryInterface $validationErrorViewFactory + * @param TokenStorage $tokenStorage */ public function __construct( ViewHandlerInterface $viewHandler, CommandBus $bus, ValidatorInterface $validator, - ValidationErrorViewFactoryInterface $validationErrorViewFactory + ValidationErrorViewFactoryInterface $validationErrorViewFactory, + TokenStorage $tokenStorage ) { $this->viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; + $this->tokenStorage = $tokenStorage; } /** @@ -63,13 +73,16 @@ public function __invoke(Request $request): Response { $addressModel = Address::createFromRequest($request); - $validationResults = $this->validator->validate($addressModel, null, 'sylius_address_book_create'); + $validationResults = $this->validator->validate($addressModel); if (0 !== count($validationResults)) { return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - $this->bus->handle(new CreateAddress($addressModel)); + /** @var ShopUserInterface $user */ + $user = $this->tokenStorage->getToken()->getUser(); + + $this->bus->handle(new CreateAddress($addressModel, $user->getEmail())); return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index 4021a167e..8703e56b5 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -9,7 +9,6 @@ use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; final class CreateAddressHandler @@ -35,36 +34,36 @@ final class CreateAddressHandler private $provinceRepository; /** - * @var TokenStorageInterface + * @var RepositoryInterface */ - private $tokenStorage; + private $customerRepository; /** * @param RepositoryInterface $addressRepository * @param RepositoryInterface $countryRepository * @param RepositoryInterface $provinceRepository + * @param RepositoryInterface $customerRepository * @param FactoryInterface $addressFactory - * @param TokenStorageInterface $tokenStorage */ public function __construct( RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, - FactoryInterface $addressFactory, - TokenStorageInterface $tokenStorage + RepositoryInterface $customerRepository, + FactoryInterface $addressFactory ) { $this->addressRepository = $addressRepository; $this->countryRepository = $countryRepository; $this->provinceRepository = $provinceRepository; $this->addressFactory = $addressFactory; - $this->tokenStorage = $tokenStorage; + $this->customerRepository = $customerRepository; } public function handle(CreateAddress $command): void { - $user = $this->tokenStorage->getToken()->getUser(); - $customer = $user->getCustomer(); + $customer = $this->customerRepository->findOneBy(['email' => $command->userEmail()]); + $this->assertCustomerExists($customer); $this->assertCountryExists($command->countryCode()); /** @var AddressInterface $address */ @@ -88,6 +87,14 @@ public function handle(CreateAddress $command): void $this->addressRepository->add($address); } + /** + * @param $customer + */ + private function assertCustomerExists($customer) + { + Assert::notNull($customer, 'Customer does not exists!'); + } + /** * @param string $countryCode */ diff --git a/src/Model/Address.php b/src/Model/Address.php index 478151a11..2896723d1 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -9,11 +9,6 @@ final class Address { - /** - * @var int - */ - private $id; - /** * @var string */ @@ -71,7 +66,6 @@ final class Address * @param string $street * @param string $countryCode * @param string $postcode - * @param string $id * @param string $provinceName * @param string $provinceCode * @param string $company @@ -84,7 +78,6 @@ private function __construct( $street, $countryCode, $postcode, - $id = null, $provinceName = null, $provinceCode = null, $phoneNumber = null, @@ -96,7 +89,6 @@ private function __construct( $this->street = $street; $this->countryCode = $countryCode; $this->postcode = $postcode; - $this->id = $id; $this->provinceName = $provinceName; $this->provinceCode = $provinceCode; $this->phoneNumber = $phoneNumber; @@ -124,7 +116,6 @@ public static function createFromArray(array $address) $address['street'], $address['countryCode'], $address['postcode'], - $address['id'] ?? null, $address['provinceName'] ?? null, $address['provinceCode'] ?? null, $address['phoneNumber'] ?? null, @@ -146,7 +137,6 @@ public static function createFromRequest(Request $request) $request->request->get('street'), $request->request->get('countryCode'), $request->request->get('postcode'), - $request->attributes->get('id') ?? $request->request->get('id'), $request->request->get('provinceName'), $request->request->get('provinceCode'), $request->request->get('phoneNumber'), @@ -154,14 +144,6 @@ public static function createFromRequest(Request $request) ); } - /** - * @return mixed - */ - public function id() - { - return $this->id; - } - /** * @return string */ diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php index 39c5bf625..49a4be426 100644 --- a/src/Request/RemoveAddressRequest.php +++ b/src/Request/RemoveAddressRequest.php @@ -14,18 +14,12 @@ final class RemoveAddressRequest */ private $id; - /** - * @param Request $request - */ public function __construct(Request $request) { $this->id = $request->attributes->get('id'); } - /** - * @return RemoveAddress - */ - public function getCommand() + public function getCommand(): RemoveAddress { return new RemoveAddress($this->id); } diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index 46da25fff..8b6f800cd 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -19,10 +19,7 @@ public function __construct(Request $request) $this->id = $request->attributes->get('id'); } - /** - * @return SetDefaultAddress - */ - public function getCommand() + public function getCommand(): SetDefaultAddress { return new SetDefaultAddress($this->id); } diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index 96406f50b..aa2d43f8f 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -9,6 +9,7 @@ + + - diff --git a/src/Resources/config/validation/AddressModelRequest.xml b/src/Resources/config/validation/AddressModelRequest.xml index 036e62c8c..7466a8f03 100644 --- a/src/Resources/config/validation/AddressModelRequest.xml +++ b/src/Resources/config/validation/AddressModelRequest.xml @@ -2,94 +2,64 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/Application/app/config/config.yml b/tests/Application/app/config/config.yml index 8d6f145a0..ae7c44abe 100644 --- a/tests/Application/app/config/config.yml +++ b/tests/Application/app/config/config.yml @@ -36,7 +36,8 @@ framework: doctrine: dbal: driver: "pdo_sqlite" - path: "%kernel.cache_dir%/db.sql" + path: "/run/shm/sylius/cache/test/db.sql" +# path: "%kernel.cache_dir%/db.sql" charset: UTF8 fos_rest: From 9581b43346cfb9ff8c521b2481f91711bbe00457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 6 Nov 2017 11:55:15 +0100 Subject: [PATCH 28/34] [Address-book] Refactor --- spec/Command/RemoveAddressSpec.php | 13 ++-- spec/Command/SetDefaultAddressSpec.php | 13 ++-- spec/Command/UpdateAddressSpec.php | 7 ++- spec/Handler/RemoveAddressHandlerSpec.php | 42 +++++-------- spec/Handler/SetDefaultAddressHandlerSpec.php | 51 ++++++++-------- .../UpdateAddressBookAddressHandlerSpec.php | 59 ++++++++----------- src/Command/CreateAddress.php | 4 +- src/Command/RemoveAddress.php | 17 +++++- src/Command/SetDefaultAddress.php | 19 +++++- src/Command/UpdateAddress.php | 26 +++++++- .../AddressBook/CreateAddressAction.php | 6 +- .../AddressBook/RemoveAddressAction.php | 21 ++++++- ...ddress.php => SetDefaultAddressAction.php} | 19 +++++- .../AddressBook/UpdateAddressAction.php | 13 ++-- src/Handler/CreateAddressHandler.php | 4 ++ src/Handler/RemoveAddressHandler.php | 18 +++--- src/Handler/SetDefaultAddressHandler.php | 21 ++++--- .../UpdateAddressBookAddressHandler.php | 24 +++++--- src/Request/RemoveAddressRequest.php | 6 -- src/Request/SetDefaultAddressRequest.php | 6 -- .../config/services/actions/address_book.xml | 4 +- src/Resources/config/services/handlers.xml | 6 +- tests/DataFixtures/ORM/customer.yml | 2 +- tests/Request/RemoveAddressRequestTest.php | 23 -------- .../Request/SetDefaultAddressRequestTest.php | 23 -------- 25 files changed, 233 insertions(+), 214 deletions(-) rename src/Controller/AddressBook/{SetDefaultAddress.php => SetDefaultAddressAction.php} (77%) delete mode 100644 tests/Request/RemoveAddressRequestTest.php delete mode 100644 tests/Request/SetDefaultAddressRequestTest.php diff --git a/spec/Command/RemoveAddressSpec.php b/spec/Command/RemoveAddressSpec.php index aa33bf4df..89c5d8404 100644 --- a/spec/Command/RemoveAddressSpec.php +++ b/spec/Command/RemoveAddressSpec.php @@ -5,22 +5,21 @@ namespace spec\Sylius\ShopApiPlugin\Command; use PhpSpec\ObjectBehavior; -use Sylius\ShopApiPlugin\Command\RemoveAddress; final class RemoveAddressSpec extends ObjectBehavior { - function it_is_initializable() + function let() { - $this->shouldHaveType(RemoveAddress::class); + $this->beConstructedWith('ADDRESS_ID', 'user@email.com'); } - function let() + function it_has_id() { - $this->beConstructedWith('1'); + $this->id()->shouldReturn('ADDRESS_ID'); } - function it_has_id() + function it_has_user_email() { - $this->id()->shouldReturn('1'); + $this->userEmail()->shouldReturn('user@email.com'); } } diff --git a/spec/Command/SetDefaultAddressSpec.php b/spec/Command/SetDefaultAddressSpec.php index f84602889..c5f153361 100644 --- a/spec/Command/SetDefaultAddressSpec.php +++ b/spec/Command/SetDefaultAddressSpec.php @@ -5,22 +5,21 @@ namespace spec\Sylius\ShopApiPlugin\Command; use PhpSpec\ObjectBehavior; -use Sylius\ShopApiPlugin\Command\SetDefaultAddress; final class SetDefaultAddressSpec extends ObjectBehavior { - function it_is_initializable() - { - $this->shouldHaveType(SetDefaultAddress::class); - } - function let() { - $this->beConstructedWith('ADDRESS_ID'); + $this->beConstructedWith('ADDRESS_ID', 'user@email.com'); } function it_has_id() { $this->id()->shouldReturn('ADDRESS_ID'); } + + function it_has_user_email() + { + $this->userEmail()->shouldReturn('user@email.com'); + } } diff --git a/spec/Command/UpdateAddressSpec.php b/spec/Command/UpdateAddressSpec.php index bfa6110b0..7f9613da2 100644 --- a/spec/Command/UpdateAddressSpec.php +++ b/spec/Command/UpdateAddressSpec.php @@ -29,7 +29,7 @@ function let() 'provinceCode' => 'GB-GL', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ])); + ]), 'user@email.com', 'ADDRESS_ID'); } function it_has_address_id() @@ -81,4 +81,9 @@ function it_has_phone_number() { $this->phoneNumber()->shouldReturn('0912538092'); } + + function it_has_user_email() + { + $this->userEmail()->shouldReturn('user@email.com'); + } } diff --git a/spec/Handler/RemoveAddressHandlerSpec.php b/spec/Handler/RemoveAddressHandlerSpec.php index b010c9865..b9eb1abd1 100644 --- a/spec/Handler/RemoveAddressHandlerSpec.php +++ b/spec/Handler/RemoveAddressHandlerSpec.php @@ -4,7 +4,6 @@ namespace spec\Sylius\ShopApiPlugin\Handler; -use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use PhpSpec\ObjectBehavior; use Sylius\Bundle\CoreBundle\Doctrine\ORM\AddressRepository; use Sylius\Component\Core\Model\AddressInterface; @@ -14,97 +13,84 @@ use Sylius\Component\Core\Repository\OrderRepositoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; final class RemoveAddressHandlerSpec extends ObjectBehavior { function let( RepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, - TokenStorageInterface $tokenStorage + RepositoryInterface $shopUserRepository ) { $this->beConstructedWith( $addressRepository, $orderRepository, - $tokenStorage + $shopUserRepository ); } function it_removes_address_from_address_book( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, AddressRepository $addressRepository, OrderRepositoryInterface $orderRepository, + RepositoryInterface $shopUserRepository, AddressInterface $address ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + $address->getCustomer()->willReturn($customer); $customer->getId()->willReturn('USER_ID'); $shopUser->getId()->willReturn('USER_ID'); - $address->getCustomer()->willReturn($customer); $orderRepository->findBy(['billingAddress' => $address])->willReturn([]); $orderRepository->findBy(['shippingAddress' => $address])->willReturn([]); $addressRepository->remove($address)->shouldBeCalled(); - $this->handle(new RemoveAddress('ADDRESS_ID')); + $this->handle(new RemoveAddress('ADDRESS_ID', 'user@email.com')); } function it_throws_an_exception_when_deleting_address_associated_with_order( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, AddressRepository $addressRepository, OrderRepositoryInterface $orderRepository, + RepositoryInterface $shopUserRepository, AddressInterface $address, OrderInterface $order ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + $address->getCustomer()->willReturn($customer); $customer->getId()->willReturn('USER_ID'); $shopUser->getId()->willReturn('USER_ID'); - $address->getCustomer()->willReturn($customer); $orderRepository->findBy(['billingAddress' => $address])->willReturn($order); $orderRepository->findBy(['shippingAddress' => $address])->willReturn($order); $addressRepository->remove($address)->shouldNotBeCalled(); - $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID')]); + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID', 'user@email.com')]); } function it_trows_exception_if_address_does_not_belong_to_current_user( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, AddressRepository $addressRepository, + RepositoryInterface $shopUserRepository, AddressInterface $address ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + $address->getCustomer()->willReturn($customer); $customer->getId()->willReturn('USER_ID_1'); $shopUser->getId()->willReturn('USER_ID_2'); - $address->getCustomer()->willReturn($customer); $addressRepository->remove($address)->shouldNotBeCalled(); - $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID')]); + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID', 'user@email.com')]); } } diff --git a/spec/Handler/SetDefaultAddressHandlerSpec.php b/spec/Handler/SetDefaultAddressHandlerSpec.php index 829330492..0361217b9 100644 --- a/spec/Handler/SetDefaultAddressHandlerSpec.php +++ b/spec/Handler/SetDefaultAddressHandlerSpec.php @@ -4,40 +4,40 @@ namespace spec\Sylius\ShopApiPlugin\Handler; -use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use PhpSpec\ObjectBehavior; use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\Customer; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\CustomerRepositoryInterface; +use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\SetDefaultAddress; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; final class SetDefaultAddressHandlerSpec extends ObjectBehavior { function let( CustomerRepositoryInterface $customerRepository, AddressRepositoryInterface $addressRepository, - TokenStorageInterface $tokenStorage + RepositoryInterface $shopUserRepository ) { - $this->beConstructedWith($customerRepository, $addressRepository, $tokenStorage); + $this->beConstructedWith( + $customerRepository, + $addressRepository, + $shopUserRepository + ); } function it_handles_setting_default_address_for_user( AddressInterface $address, AddressRepositoryInterface $addressRepository, - TokenStorageInterface $tokenStorage, + RepositoryInterface $shopUserRepository, ShopUserInterface $user, - Customer $customer, - JWTUserToken $userToken + Customer $customer ) { + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($user); $addressRepository->find('ADDRESS_ID')->willReturn($address); - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($user); $user->getCustomer()->willReturn($customer); - $address->getCustomer()->willReturn($customer); $customer->getId()->willReturn('USER_ID'); @@ -45,44 +45,45 @@ function it_handles_setting_default_address_for_user( $customer->setDefaultAddress($address)->shouldBeCalled(); - $this->handle(new SetDefaultAddress('ADDRESS_ID')); + $this->handle(new SetDefaultAddress('ADDRESS_ID', 'user@email.com')); } function it_trows_exception_if_address_does_not_belong_to_current_user( AddressInterface $address, AddressRepositoryInterface $addressRepository, - TokenStorageInterface $tokenStorage, + RepositoryInterface $shopUserRepository, ShopUserInterface $user, - Customer $customer, - JWTUserToken $userToken + Customer $customer ) { + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($user); $addressRepository->find('ADDRESS_ID')->willReturn($address); - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($user); $user->getCustomer()->willReturn($customer); - $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID_1'); $user->getId()->willReturn('USER_ID_2'); - $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new SetDefaultAddress('ADDRESS_ID')]); + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [ + new SetDefaultAddress('ADDRESS_ID', 'user@email.com'), + ]); } function it_trows_exception_if_address_is_not_associated_with_any_user( AddressInterface $address, AddressRepositoryInterface $addressRepository, - TokenStorageInterface $tokenStorage, - ShopUserInterface $user, - JWTUserToken $userToken + RepositoryInterface $shopUserRepository, + ShopUserInterface $user ) { + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($user); $addressRepository->find('ADDRESS_ID')->willReturn($address); - $address->getCustomer()->willReturn(null); - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($user); + $address->getCustomer()->willReturn(null); $user->getId()->shouldNotBeCalled(); - $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new SetDefaultAddress('ADDRESS_ID')]); + + $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [ + new SetDefaultAddress('ADDRESS_ID', 'user@email.com'), + ]); } } diff --git a/spec/Handler/UpdateAddressBookAddressHandlerSpec.php b/spec/Handler/UpdateAddressBookAddressHandlerSpec.php index a7050fabc..dfcebf71c 100644 --- a/spec/Handler/UpdateAddressBookAddressHandlerSpec.php +++ b/spec/Handler/UpdateAddressBookAddressHandlerSpec.php @@ -4,7 +4,6 @@ namespace spec\Sylius\ShopApiPlugin\Handler; -use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use PhpSpec\ObjectBehavior; use Sylius\Component\Addressing\Model\CountryInterface; use Sylius\Component\Addressing\Model\ProvinceInterface; @@ -15,7 +14,6 @@ use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\UpdateAddress; use Sylius\ShopApiPlugin\Model\Address; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; final class UpdateAddressBookAddressHandlerSpec extends ObjectBehavior { @@ -23,37 +21,35 @@ function let( RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, - FactoryInterface $addressFactory, - TokenStorageInterface $tokenStorage + RepositoryInterface $shopUserRepository, + FactoryInterface $addressFactory ) { $this->beConstructedWith( $addressRepository, $countryRepository, $provinceRepository, - $addressFactory, - $tokenStorage + $shopUserRepository, + $addressFactory ); } function it_updates_address( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, + RepositoryInterface $shopUserRepository, ProvinceInterface $province, CountryInterface $country, AddressInterface $address ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); $address->getCustomer()->willReturn($customer); + $shopUser->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID'); $shopUser->getId()->willReturn('USER_ID'); @@ -90,24 +86,22 @@ function it_updates_address( 'provinceCode' => 'GB-GL', 'company' => 'Sherlock ltd.', 'phoneNumber' => '0912538092', - ]))); + ]), 'user@email.com', 'ADDRESS_ID')); } function it_throws_an_exception_if_current_user_is_not_address_owner( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, RepositoryInterface $addressRepository, + RepositoryInterface $shopUserRepository, AddressInterface $address ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); $address->getCustomer()->willReturn($customer); + $shopUser->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID_1'); $shopUser->getId()->willReturn('USER_ID_2'); @@ -123,26 +117,23 @@ function it_throws_an_exception_if_current_user_is_not_address_owner( 'postcode' => 'NWB', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ]))]); + ]), 'user@email.com', 'ADDRESS_ID')]); } function it_throws_an_exception_if_country_does_not_exists( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, - CountryInterface $country, + RepositoryInterface $shopUserRepository, AddressInterface $address ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + $shopUser->getCustomer()->willReturn($customer); $address->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID'); $shopUser->getId()->willReturn('USER_ID'); @@ -161,27 +152,25 @@ function it_throws_an_exception_if_country_does_not_exists( 'provinceCode' => 'GB-GL', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ]))]); + ]), 'user@email.com', 'ADDRESS_ID')]); } function it_throws_an_exception_if_province_code_does_not_exists( - TokenStorageInterface $tokenStorage, - JWTUserToken $userToken, ShopUserInterface $shopUser, CustomerInterface $customer, RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, + RepositoryInterface $shopUserRepository, CountryInterface $country, AddressInterface $address ) { - $tokenStorage->getToken()->willReturn($userToken); - $userToken->getUser()->willReturn($shopUser); - $shopUser->getCustomer()->willReturn($customer); - + $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); $address->getCustomer()->willReturn($customer); + $shopUser->getCustomer()->willReturn($customer); + $customer->getId()->willReturn('USER_ID'); $shopUser->getId()->willReturn('USER_ID'); @@ -215,6 +204,6 @@ function it_throws_an_exception_if_province_code_does_not_exists( 'provinceCode' => 'WRONG_PROVINCE_CODE', 'phoneNumber' => '0912538092', 'company' => 'Sherlock ltd.', - ]))]); + ]), 'user@email.com', 'ADDRESS_ID')]); } } diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index 9236e0d49..3ac4a884f 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -101,9 +101,9 @@ public function phoneNumber(): ?string } /** - * @return null|string + * @return string */ - public function userEmail(): ?string + public function userEmail(): string { return $this->userEmail; } diff --git a/src/Command/RemoveAddress.php b/src/Command/RemoveAddress.php index ba37ea284..bed9685c6 100644 --- a/src/Command/RemoveAddress.php +++ b/src/Command/RemoveAddress.php @@ -11,12 +11,19 @@ class RemoveAddress */ private $id; + /** + * @var string + */ + private $userEmail; + /** * @param $id + * @param string $userEmail */ - public function __construct($id) + public function __construct($id, string $userEmail) { $this->id = $id; + $this->userEmail = $userEmail; } /** @@ -26,4 +33,12 @@ public function id() { return $this->id; } + + /** + * @return string + */ + public function userEmail() + { + return $this->userEmail; + } } diff --git a/src/Command/SetDefaultAddress.php b/src/Command/SetDefaultAddress.php index ed05af1a2..9de929b4c 100644 --- a/src/Command/SetDefaultAddress.php +++ b/src/Command/SetDefaultAddress.php @@ -4,19 +4,26 @@ namespace Sylius\ShopApiPlugin\Command; -class SetDefaultAddress +final class SetDefaultAddress { /** * @var mixed */ private $id; + /** + * @var string + */ + private $userEmail; + /** * @param $id + * @param string $userEmail */ - public function __construct($id) + public function __construct($id, string $userEmail) { $this->id = $id; + $this->userEmail = $userEmail; } /** @@ -26,4 +33,12 @@ public function id() { return $this->id; } + + /** + * @return string + */ + public function userEmail() + { + return $this->userEmail; + } } diff --git a/src/Command/UpdateAddress.php b/src/Command/UpdateAddress.php index 27dd56320..cbcebdcb1 100644 --- a/src/Command/UpdateAddress.php +++ b/src/Command/UpdateAddress.php @@ -13,12 +13,26 @@ final class UpdateAddress */ private $address; + /** + * @var string + */ + private $userEmail; + + /** + * @var string + */ + private $addressId; + /** * @param Address $address + * @param string $userEmail + * @param string $addressId */ - public function __construct(Address $address) + public function __construct(Address $address, string $userEmail, string $addressId) { $this->address = $address; + $this->userEmail = $userEmail; + $this->addressId = $addressId; } /** @@ -26,7 +40,7 @@ public function __construct(Address $address) */ public function id(): string { - return $this->address->id(); + return $this->addressId; } /** @@ -100,4 +114,12 @@ public function phoneNumber(): ?string { return $this->address->phoneNumber(); } + + /** + * @return string + */ + public function userEmail(): string + { + return $this->userEmail; + } } diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index 909b83cac..c51a37b56 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -79,10 +79,10 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - /** @var ShopUserInterface $user */ - $user = $this->tokenStorage->getToken()->getUser(); + /** @var ShopUserInterface $shopUser */ + $shopUser = $this->tokenStorage->getToken()->getUser(); - $this->bus->handle(new CreateAddress($addressModel, $user->getEmail())); + $this->bus->handle(new CreateAddress($addressModel, $shopUser->getEmail())); return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } diff --git a/src/Controller/AddressBook/RemoveAddressAction.php b/src/Controller/AddressBook/RemoveAddressAction.php index c837acf0e..1b635a0fd 100644 --- a/src/Controller/AddressBook/RemoveAddressAction.php +++ b/src/Controller/AddressBook/RemoveAddressAction.php @@ -7,10 +7,13 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; +use Sylius\Component\Core\Model\ShopUserInterface; +use Sylius\ShopApiPlugin\Command\RemoveAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactory; use Sylius\ShopApiPlugin\Request\RemoveAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; final class RemoveAddressAction @@ -35,22 +38,30 @@ final class RemoveAddressAction */ private $bus; + /** + * @var TokenStorageInterface + */ + private $tokenStorage; + /** * @param ViewHandlerInterface $viewHandler * @param ValidatorInterface $validator * @param ValidationErrorViewFactory $validationErrorViewFactory * @param CommandBus $bus + * @param TokenStorageInterface $tokenStorage */ public function __construct( ViewHandlerInterface $viewHandler, ValidatorInterface $validator, ValidationErrorViewFactory $validationErrorViewFactory, - CommandBus $bus + CommandBus $bus, + TokenStorageInterface $tokenStorage ) { $this->viewHandler = $viewHandler; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; $this->bus = $bus; + $this->tokenStorage = $tokenStorage; } public function __invoke(Request $request): Response @@ -63,7 +74,13 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - $this->bus->handle($removeAddressRequest->getCommand()); + /** @var ShopUserInterface $shopUser */ + $shopUser = $this->tokenStorage->getToken()->getUser(); + + $this->bus->handle(new RemoveAddress( + $request->attributes->get('id'), + $shopUser->getEmail() + )); return $this->viewHandler->handle(View::create('', Response::HTTP_NO_CONTENT)); } diff --git a/src/Controller/AddressBook/SetDefaultAddress.php b/src/Controller/AddressBook/SetDefaultAddressAction.php similarity index 77% rename from src/Controller/AddressBook/SetDefaultAddress.php rename to src/Controller/AddressBook/SetDefaultAddressAction.php index a35e5d6c7..e79d7aa02 100644 --- a/src/Controller/AddressBook/SetDefaultAddress.php +++ b/src/Controller/AddressBook/SetDefaultAddressAction.php @@ -7,13 +7,15 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; +use Sylius\ShopApiPlugin\Command\SetDefaultAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; use Sylius\ShopApiPlugin\Request\SetDefaultAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; -final class SetDefaultAddress +final class SetDefaultAddressAction { /** * @var ViewHandlerInterface @@ -35,22 +37,30 @@ final class SetDefaultAddress */ private $validationErrorViewFactory; + /** + * @var TokenStorageInterface + */ + private $tokenStorage; + /** * @param ViewHandlerInterface $viewHandler * @param CommandBus $bus * @param ValidatorInterface $validator * @param ValidationErrorViewFactoryInterface $validationErrorViewFactory + * @param TokenStorageInterface $tokenStorage */ public function __construct( ViewHandlerInterface $viewHandler, CommandBus $bus, ValidatorInterface $validator, - ValidationErrorViewFactoryInterface $validationErrorViewFactory + ValidationErrorViewFactoryInterface $validationErrorViewFactory, + TokenStorageInterface $tokenStorage ) { $this->viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; + $this->tokenStorage = $tokenStorage; } /** @@ -68,7 +78,10 @@ public function __invoke(Request $request) return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - $this->bus->handle($setDefaultAddressRequest->getCommand()); + $this->bus->handle(new SetDefaultAddress( + $request->attributes->get('id'), + $this->tokenStorage->getToken()->getUser()->getEmail() + )); return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } diff --git a/src/Controller/AddressBook/UpdateAddressAction.php b/src/Controller/AddressBook/UpdateAddressAction.php index f2cce89a6..bbb1ace6d 100644 --- a/src/Controller/AddressBook/UpdateAddressAction.php +++ b/src/Controller/AddressBook/UpdateAddressAction.php @@ -7,6 +7,8 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; +use Sylius\Component\Core\Model\AddressInterface; +use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\ShopApiPlugin\Command\UpdateAddress; use Sylius\ShopApiPlugin\Factory\AddressBookViewFactoryInterface; @@ -85,19 +87,22 @@ public function __invoke(Request $request, $id): Response { $addressModel = Address::createFromRequest($request); - $validationResults = $this->validator->validate($addressModel, null, 'sylius_address_book_update'); + $validationResults = $this->validator->validate($addressModel); if (0 !== count($validationResults)) { return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - $this->bus->handle(new UpdateAddress($addressModel)); + /** @var ShopUserInterface $customer */ + $shopUser = $this->tokenStorage->getToken()->getUser(); + $this->bus->handle(new UpdateAddress($addressModel, $shopUser->getEmail(), $id)); + + /** @var AddressInterface $updatedAddress */ $updatedAddress = $this->addressRepository->findOneBy(['id' => $id]); - $customer = $this->tokenStorage->getToken()->getUser()->getCustomer(); return $this->viewHandler->handle(View::create( - $this->addressBookViewFactory->create($updatedAddress, $customer), + $this->addressBookViewFactory->create($updatedAddress, $shopUser->getCustomer()), Response::HTTP_OK) ); } diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index 8703e56b5..1c0283f8d 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -6,6 +6,7 @@ use Sylius\Component\Addressing\Model\ProvinceInterface; use Sylius\Component\Core\Model\AddressInterface; +use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; @@ -61,6 +62,7 @@ public function __construct( public function handle(CreateAddress $command): void { + /** @var CustomerInterface $shopUser */ $customer = $this->customerRepository->findOneBy(['email' => $command->userEmail()]); $this->assertCustomerExists($customer); @@ -84,6 +86,7 @@ public function handle(CreateAddress $command): void } $customer->addAddress($address); + $this->addressRepository->add($address); } @@ -105,6 +108,7 @@ private function assertCountryExists(string $countryCode): void /** * @param string $provinceCode + * * @return ProvinceInterface */ private function checkProvinceExists(string $provinceCode): ProvinceInterface diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 24e56656a..06ae2e58b 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -9,8 +9,8 @@ use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; +use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; final class RemoveAddressHandler @@ -26,31 +26,31 @@ final class RemoveAddressHandler private $orderRepository; /** - * @var TokenStorageInterface + * @var RepositoryInterface */ - private $tokenStorage; + private $shopUserRepository; /** * @param AddressRepositoryInterface $addressRepository * @param OrderRepositoryInterface $orderRepository - * @param TokenStorageInterface $tokenStorage + * @param RepositoryInterface $shopUserRepository */ - public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, TokenStorageInterface $tokenStorage) + public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, RepositoryInterface $shopUserRepository) { $this->addressRepository = $addressRepository; $this->orderRepository = $orderRepository; - $this->tokenStorage = $tokenStorage; + $this->shopUserRepository = $shopUserRepository; } public function handle(RemoveAddress $removeAddress) { - /** @var ShopUserInterface $user */ - $user = $this->tokenStorage->getToken()->getUser(); + /** @var ShopUserInterface $shopUser */ + $shopUser = $this->shopUserRepository->findOneBy(['username' => $removeAddress->userEmail()]); /** @var AddressInterface $address */ $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id()]); - $this->assertCurrentUserIsOwner($address, $user); + $this->assertCurrentUserIsOwner($address, $shopUser); $this->assertOrderWithAddressNotExists($address); $this->addressRepository->remove($address); diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index b15be7645..d621e540f 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -6,12 +6,11 @@ use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\CustomerInterface; -use Sylius\Component\Core\Model\ShopUser; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\CustomerRepositoryInterface; +use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\SetDefaultAddress; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; final class SetDefaultAddressHandler @@ -27,36 +26,36 @@ final class SetDefaultAddressHandler private $addressRepository; /** - * @var TokenStorageInterface + * @var RepositoryInterface */ - private $tokenStorage; + private $shopUserRepository; /** * @param CustomerRepositoryInterface $customerRepository * @param AddressRepositoryInterface $addressRepository - * @param TokenStorageInterface $tokenStorage + * @param RepositoryInterface $shopUserRepository */ public function __construct( CustomerRepositoryInterface $customerRepository, AddressRepositoryInterface $addressRepository, - TokenStorageInterface $tokenStorage + RepositoryInterface $shopUserRepository ) { $this->customerRepository = $customerRepository; $this->addressRepository = $addressRepository; - $this->tokenStorage = $tokenStorage; + $this->shopUserRepository = $shopUserRepository; } public function handle(SetDefaultAddress $setDefaultAddress): void { /** @var AddressInterface $address */ $address = $this->addressRepository->find($setDefaultAddress->id()); - /** @var ShopUser */ - $user = $this->tokenStorage->getToken()->getUser(); + /** @var ShopUserInterface $shopUser */ + $shopUser = $this->shopUserRepository->findOneBy(['username' => $setDefaultAddress->userEmail()]); - $this->assertCurrentUserIsOwner($address, $user); + $this->assertCurrentUserIsOwner($address, $shopUser); /** @var CustomerInterface $customer */ - $customer = $user->getCustomer(); + $customer = $shopUser->getCustomer(); $customer->setDefaultAddress($address); $this->customerRepository->add($customer); diff --git a/src/Handler/UpdateAddressBookAddressHandler.php b/src/Handler/UpdateAddressBookAddressHandler.php index 100d60dcd..982bbffbb 100644 --- a/src/Handler/UpdateAddressBookAddressHandler.php +++ b/src/Handler/UpdateAddressBookAddressHandler.php @@ -9,7 +9,6 @@ use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\UpdateAddress; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Webmozart\Assert\Assert; final class UpdateAddressBookAddressHandler @@ -35,38 +34,40 @@ final class UpdateAddressBookAddressHandler private $provinceRepository; /** - * @var TokenStorageInterface + * @var RepositoryInterface */ - private $tokenStorage; + private $shopUserRepository; /** * @param RepositoryInterface $addressRepository * @param RepositoryInterface $countryRepository * @param RepositoryInterface $provinceRepository + * @param RepositoryInterface $shopUserRepository * @param FactoryInterface $addressFactory - * @param TokenStorageInterface $tokenStorage */ public function __construct( RepositoryInterface $addressRepository, RepositoryInterface $countryRepository, RepositoryInterface $provinceRepository, - FactoryInterface $addressFactory, - TokenStorageInterface $tokenStorage + RepositoryInterface $shopUserRepository, + FactoryInterface $addressFactory ) { $this->addressRepository = $addressRepository; $this->countryRepository = $countryRepository; $this->provinceRepository = $provinceRepository; $this->addressFactory = $addressFactory; - $this->tokenStorage = $tokenStorage; + $this->shopUserRepository = $shopUserRepository; } public function handle(UpdateAddress $command): void { /** @var AddressInterface $address */ $address = $this->addressRepository->findOneBy(['id' => $command->id()]); - $user = $this->tokenStorage->getToken()->getUser(); + /** @var ShopUserInterface $shopUser */ + $shopUser = $this->shopUserRepository->findOneBy(['username' => $command->userEmail()]); - $this->assertCurrentUserIsOwner($address, $user); + $this->assertAddressExists($address); + $this->assertCurrentUserIsOwner($address, $shopUser); $this->assertCountryExists($command->countryCode()); /** @var AddressInterface $address */ @@ -104,4 +105,9 @@ private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInt Assert::notNull($address->getCustomer(), 'Address is not associated with any user'); Assert::eq($address->getCustomer(), $user->getCustomer(), 'Current user is not owner of this address'); } + + private function assertAddressExists($address) + { + Assert::notNull($address, 'Address does not exist!'); + } } diff --git a/src/Request/RemoveAddressRequest.php b/src/Request/RemoveAddressRequest.php index 49a4be426..6fec62f28 100644 --- a/src/Request/RemoveAddressRequest.php +++ b/src/Request/RemoveAddressRequest.php @@ -4,7 +4,6 @@ namespace Sylius\ShopApiPlugin\Request; -use Sylius\ShopApiPlugin\Command\RemoveAddress; use Symfony\Component\HttpFoundation\Request; final class RemoveAddressRequest @@ -18,9 +17,4 @@ public function __construct(Request $request) { $this->id = $request->attributes->get('id'); } - - public function getCommand(): RemoveAddress - { - return new RemoveAddress($this->id); - } } diff --git a/src/Request/SetDefaultAddressRequest.php b/src/Request/SetDefaultAddressRequest.php index 8b6f800cd..fbf889c7f 100644 --- a/src/Request/SetDefaultAddressRequest.php +++ b/src/Request/SetDefaultAddressRequest.php @@ -4,7 +4,6 @@ namespace Sylius\ShopApiPlugin\Request; -use Sylius\ShopApiPlugin\Command\SetDefaultAddress; use Symfony\Component\HttpFoundation\Request; final class SetDefaultAddressRequest @@ -18,9 +17,4 @@ public function __construct(Request $request) { $this->id = $request->attributes->get('id'); } - - public function getCommand(): SetDefaultAddress - { - return new SetDefaultAddress($this->id); - } } diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index aa2d43f8f..2a7cce92e 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -25,6 +25,7 @@ + + diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index 4c563b8b1..2ff51450f 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -165,21 +165,21 @@ - + - + + - diff --git a/tests/DataFixtures/ORM/customer.yml b/tests/DataFixtures/ORM/customer.yml index b82b2ad05..e74c46e0b 100644 --- a/tests/DataFixtures/ORM/customer.yml +++ b/tests/DataFixtures/ORM/customer.yml @@ -27,5 +27,5 @@ Sylius\Component\Core\Model\Customer: hater: firstName: "Slade" lastName: "Wilson" - email: "slade@wilson.com" + email: "hater@queen.com" emailCanonical: "slade@queen.com" diff --git a/tests/Request/RemoveAddressRequestTest.php b/tests/Request/RemoveAddressRequestTest.php deleted file mode 100644 index c27b1394a..000000000 --- a/tests/Request/RemoveAddressRequestTest.php +++ /dev/null @@ -1,23 +0,0 @@ - '1'])); - - $this->assertEquals($removeAddressRequest->getCommand(), new RemoveAddress('1')); - } -} diff --git a/tests/Request/SetDefaultAddressRequestTest.php b/tests/Request/SetDefaultAddressRequestTest.php deleted file mode 100644 index 8a2e6271d..000000000 --- a/tests/Request/SetDefaultAddressRequestTest.php +++ /dev/null @@ -1,23 +0,0 @@ - '1'])); - - $this->assertEquals($setDefaultAddressRequest->getCommand(), new SetDefaultAddress('1')); - } -} From 338b28d05c9d79917dec30ed46fa58b8ccb210ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 6 Nov 2017 11:57:52 +0100 Subject: [PATCH 29/34] [Address-book] Removed test db hack --- tests/Application/app/config/config.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/Application/app/config/config.yml b/tests/Application/app/config/config.yml index ae7c44abe..8d6f145a0 100644 --- a/tests/Application/app/config/config.yml +++ b/tests/Application/app/config/config.yml @@ -36,8 +36,7 @@ framework: doctrine: dbal: driver: "pdo_sqlite" - path: "/run/shm/sylius/cache/test/db.sql" -# path: "%kernel.cache_dir%/db.sql" + path: "%kernel.cache_dir%/db.sql" charset: UTF8 fos_rest: From db1390c55561b4ca6cfa40c6fc2b55d04fb3275c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Mon, 6 Nov 2017 12:36:51 +0100 Subject: [PATCH 30/34] [Address-book] Changed error messages --- src/Handler/RemoveAddressHandler.php | 4 ++-- src/Handler/SetDefaultAddressHandler.php | 4 ++-- src/Handler/UpdateAddressBookAddressHandler.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index 06ae2e58b..a1ad67600 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -62,11 +62,11 @@ private function assertOrderWithAddressNotExists($address) $orderShippingAddress = $this->orderRepository->findBy(['billingAddress' => $address]); /** @var OrderInterface $orderBillingAddress */ $orderBillingAddress = $this->orderRepository->findBy(['shippingAddress' => $address]); - Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders'); + Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders.'); } private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) { - Assert::eq($address->getCustomer()->getId(), $user->getId(), 'User is not owner of this address'); + Assert::eq($address->getCustomer()->getId(), $user->getId(), 'User is not owner of this address.'); } } diff --git a/src/Handler/SetDefaultAddressHandler.php b/src/Handler/SetDefaultAddressHandler.php index d621e540f..1733956cc 100644 --- a/src/Handler/SetDefaultAddressHandler.php +++ b/src/Handler/SetDefaultAddressHandler.php @@ -63,7 +63,7 @@ public function handle(SetDefaultAddress $setDefaultAddress): void private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) { - Assert::notNull($address->getCustomer(), 'Address is not associated with any user'); - Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address'); + Assert::notNull($address->getCustomer(), 'Address is not associated with any user.'); + Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address.'); } } diff --git a/src/Handler/UpdateAddressBookAddressHandler.php b/src/Handler/UpdateAddressBookAddressHandler.php index 982bbffbb..4049323c1 100644 --- a/src/Handler/UpdateAddressBookAddressHandler.php +++ b/src/Handler/UpdateAddressBookAddressHandler.php @@ -108,6 +108,6 @@ private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInt private function assertAddressExists($address) { - Assert::notNull($address, 'Address does not exist!'); + Assert::notNull($address, 'Address does not exist.'); } } From f8bbfc0972aa9ee8db0a0e284834ecf92a9cd7cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Fri, 10 Nov 2017 09:30:28 +0100 Subject: [PATCH 31/34] [Address-book] add return type --- src/Model/Address.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Model/Address.php b/src/Model/Address.php index 2896723d1..631531efa 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -100,7 +100,7 @@ private function __construct( * * @return Address */ - public static function createFromArray(array $address) + public static function createFromArray(array $address): Address { Assert::keyExists($address, 'firstName'); Assert::keyExists($address, 'lastName'); @@ -128,7 +128,7 @@ public static function createFromArray(array $address) * * @return Address */ - public static function createFromRequest(Request $request) + public static function createFromRequest(Request $request): Address { return new self( $request->request->get('firstName'), From 7772868ca69694a5198caa79d8cd4460d72e59e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Tue, 27 Feb 2018 00:59:54 +0100 Subject: [PATCH 32/34] change 'address_id to string' --- spec/Handler/SetDefaultAddressHandlerSpec.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/spec/Handler/SetDefaultAddressHandlerSpec.php b/spec/Handler/SetDefaultAddressHandlerSpec.php index 0361217b9..b891de3f6 100644 --- a/spec/Handler/SetDefaultAddressHandlerSpec.php +++ b/spec/Handler/SetDefaultAddressHandlerSpec.php @@ -35,7 +35,7 @@ function it_handles_setting_default_address_for_user( Customer $customer ) { $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($user); - $addressRepository->find('ADDRESS_ID')->willReturn($address); + $addressRepository->find(1)->willReturn($address); $user->getCustomer()->willReturn($customer); $address->getCustomer()->willReturn($customer); @@ -45,7 +45,7 @@ function it_handles_setting_default_address_for_user( $customer->setDefaultAddress($address)->shouldBeCalled(); - $this->handle(new SetDefaultAddress('ADDRESS_ID', 'user@email.com')); + $this->handle(new SetDefaultAddress(1, 'user@email.com')); } function it_trows_exception_if_address_does_not_belong_to_current_user( @@ -56,7 +56,7 @@ function it_trows_exception_if_address_does_not_belong_to_current_user( Customer $customer ) { $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($user); - $addressRepository->find('ADDRESS_ID')->willReturn($address); + $addressRepository->find(1)->willReturn($address); $user->getCustomer()->willReturn($customer); $address->getCustomer()->willReturn($customer); @@ -65,7 +65,7 @@ function it_trows_exception_if_address_does_not_belong_to_current_user( $user->getId()->willReturn('USER_ID_2'); $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [ - new SetDefaultAddress('ADDRESS_ID', 'user@email.com'), + new SetDefaultAddress(1, 'user@email.com'), ]); } @@ -76,14 +76,14 @@ function it_trows_exception_if_address_is_not_associated_with_any_user( ShopUserInterface $user ) { $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($user); - $addressRepository->find('ADDRESS_ID')->willReturn($address); + $addressRepository->find(1)->willReturn($address); $address->getCustomer()->willReturn(null); $user->getId()->shouldNotBeCalled(); $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [ - new SetDefaultAddress('ADDRESS_ID', 'user@email.com'), + new SetDefaultAddress(1, 'user@email.com'), ]); } } From f7ab829735dd363b48e6f7eacb0d69f0d6b551ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Tue, 27 Feb 2018 01:12:24 +0100 Subject: [PATCH 33/34] Fixed phpspec --- spec/Handler/RemoveAddressHandlerSpec.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/spec/Handler/RemoveAddressHandlerSpec.php b/spec/Handler/RemoveAddressHandlerSpec.php index b9eb1abd1..d0d35066b 100644 --- a/spec/Handler/RemoveAddressHandlerSpec.php +++ b/spec/Handler/RemoveAddressHandlerSpec.php @@ -10,6 +10,7 @@ use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\ShopUserInterface; +use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; @@ -17,7 +18,7 @@ final class RemoveAddressHandlerSpec extends ObjectBehavior { function let( - RepositoryInterface $addressRepository, + AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, RepositoryInterface $shopUserRepository ) { @@ -31,7 +32,7 @@ function let( function it_removes_address_from_address_book( ShopUserInterface $shopUser, CustomerInterface $customer, - AddressRepository $addressRepository, + AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, RepositoryInterface $shopUserRepository, AddressInterface $address @@ -54,7 +55,7 @@ function it_removes_address_from_address_book( function it_throws_an_exception_when_deleting_address_associated_with_order( ShopUserInterface $shopUser, CustomerInterface $customer, - AddressRepository $addressRepository, + AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, RepositoryInterface $shopUserRepository, AddressInterface $address, @@ -78,7 +79,7 @@ function it_throws_an_exception_when_deleting_address_associated_with_order( function it_trows_exception_if_address_does_not_belong_to_current_user( ShopUserInterface $shopUser, CustomerInterface $customer, - AddressRepository $addressRepository, + AddressRepositoryInterface $addressRepository, RepositoryInterface $shopUserRepository, AddressInterface $address ) { From b9efa6c0c6cfa6f6096ef69cd59b7598f602f5ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jurica=20=C5=A0eparovi=C4=87?= Date: Thu, 9 Aug 2018 18:30:10 +0200 Subject: [PATCH 34/34] Apply small fixes and add better validation --- spec/Command/CreateAddressSpec.php | 44 +----------- spec/Handler/RemoveAddressHandlerSpec.php | 66 +---------------- spec/Validator/AddressExistsValidatorSpec.php | 45 ++++++++++-- src/Command/CreateAddress.php | 70 +------------------ src/Command/RemoveAddress.php | 2 +- .../AddressBook/CreateAddressAction.php | 16 +++-- .../AddressBook/RemoveAddressAction.php | 17 +++-- .../AddressBook/SetDefaultAddressAction.php | 14 +++- .../AddressBook/UpdateAddressAction.php | 18 +++-- src/Handler/CreateAddressHandler.php | 28 ++++---- src/Handler/RemoveAddressHandler.php | 35 +--------- src/Model/Address.php | 4 +- src/Provider/CurrentUserProvider.php | 35 ++++++++++ src/Provider/CurrentUserProviderInterface.php | 12 ++++ src/Resources/config/services.xml | 4 ++ .../config/services/actions/address_book.xml | 4 ++ src/Resources/config/services/handlers.xml | 1 - src/Resources/config/services/validators.xml | 1 + src/Validator/AddressExistsValidator.php | 30 ++++++-- .../AddressBookRemoveAddressApiTest.php | 2 +- tests/DataFixtures/ORM/address.yml | 2 +- 21 files changed, 198 insertions(+), 252 deletions(-) create mode 100644 src/Provider/CurrentUserProvider.php create mode 100644 src/Provider/CurrentUserProviderInterface.php diff --git a/spec/Command/CreateAddressSpec.php b/spec/Command/CreateAddressSpec.php index 297063afe..eb2ea003d 100644 --- a/spec/Command/CreateAddressSpec.php +++ b/spec/Command/CreateAddressSpec.php @@ -25,49 +25,9 @@ function let() ]), 'user@email.com'); } - function it_has_first_name() + function it_has_address() { - $this->firstName()->shouldReturn('Sherlock'); - } - - function it_has_last_name() - { - $this->lastName()->shouldReturn('Holmes'); - } - - function it_has_company() - { - $this->company()->shouldReturn('Sherlock ltd.'); - } - - function it_has_street() - { - $this->street()->shouldReturn('Baker Street 221b'); - } - - function it_has_country_code() - { - $this->countryCode()->shouldReturn('GB'); - } - - function it_has_province_code() - { - $this->provinceCode()->shouldReturn('GB-GL'); - } - - function it_has_city() - { - $this->city()->shouldReturn('London'); - } - - function it_has_postcode() - { - $this->postcode()->shouldReturn('NWB'); - } - - function it_has_phone_number() - { - $this->phoneNumber()->shouldReturn('0912538092'); + $this->address()->shouldBeAnInstanceOf(Address::class); } function it_has_user_email() diff --git a/spec/Handler/RemoveAddressHandlerSpec.php b/spec/Handler/RemoveAddressHandlerSpec.php index d0d35066b..a12fcf21d 100644 --- a/spec/Handler/RemoveAddressHandlerSpec.php +++ b/spec/Handler/RemoveAddressHandlerSpec.php @@ -5,93 +5,31 @@ namespace spec\Sylius\ShopApiPlugin\Handler; use PhpSpec\ObjectBehavior; -use Sylius\Bundle\CoreBundle\Doctrine\ORM\AddressRepository; use Sylius\Component\Core\Model\AddressInterface; -use Sylius\Component\Core\Model\CustomerInterface; -use Sylius\Component\Core\Model\OrderInterface; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; -use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; final class RemoveAddressHandlerSpec extends ObjectBehavior { function let( AddressRepositoryInterface $addressRepository, - OrderRepositoryInterface $orderRepository, - RepositoryInterface $shopUserRepository + OrderRepositoryInterface $orderRepository ) { $this->beConstructedWith( $addressRepository, - $orderRepository, - $shopUserRepository + $orderRepository ); } function it_removes_address_from_address_book( - ShopUserInterface $shopUser, - CustomerInterface $customer, AddressRepositoryInterface $addressRepository, - OrderRepositoryInterface $orderRepository, - RepositoryInterface $shopUserRepository, AddressInterface $address ) { - $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); - $address->getCustomer()->willReturn($customer); - $customer->getId()->willReturn('USER_ID'); - $shopUser->getId()->willReturn('USER_ID'); - - $orderRepository->findBy(['billingAddress' => $address])->willReturn([]); - $orderRepository->findBy(['shippingAddress' => $address])->willReturn([]); - $addressRepository->remove($address)->shouldBeCalled(); $this->handle(new RemoveAddress('ADDRESS_ID', 'user@email.com')); } - - function it_throws_an_exception_when_deleting_address_associated_with_order( - ShopUserInterface $shopUser, - CustomerInterface $customer, - AddressRepositoryInterface $addressRepository, - OrderRepositoryInterface $orderRepository, - RepositoryInterface $shopUserRepository, - AddressInterface $address, - OrderInterface $order - ) { - $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); - $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); - - $address->getCustomer()->willReturn($customer); - $customer->getId()->willReturn('USER_ID'); - $shopUser->getId()->willReturn('USER_ID'); - - $orderRepository->findBy(['billingAddress' => $address])->willReturn($order); - $orderRepository->findBy(['shippingAddress' => $address])->willReturn($order); - - $addressRepository->remove($address)->shouldNotBeCalled(); - - $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID', 'user@email.com')]); - } - - function it_trows_exception_if_address_does_not_belong_to_current_user( - ShopUserInterface $shopUser, - CustomerInterface $customer, - AddressRepositoryInterface $addressRepository, - RepositoryInterface $shopUserRepository, - AddressInterface $address - ) { - $shopUserRepository->findOneBy(['username' => 'user@email.com'])->willReturn($shopUser); - $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); - - $address->getCustomer()->willReturn($customer); - $customer->getId()->willReturn('USER_ID_1'); - $shopUser->getId()->willReturn('USER_ID_2'); - - $addressRepository->remove($address)->shouldNotBeCalled(); - - $this->shouldThrow(\InvalidArgumentException::class)->during('handle', [new RemoveAddress('ADDRESS_ID', 'user@email.com')]); - } } diff --git a/spec/Validator/AddressExistsValidatorSpec.php b/spec/Validator/AddressExistsValidatorSpec.php index 6bfd9b953..21fe02e7e 100644 --- a/spec/Validator/AddressExistsValidatorSpec.php +++ b/spec/Validator/AddressExistsValidatorSpec.php @@ -7,26 +7,41 @@ use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Sylius\Component\Core\Model\AddressInterface; +use Sylius\Component\Core\Model\CustomerInterface; +use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; +use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface; use Sylius\ShopApiPlugin\Validator\Constraints\AddressExists; use Symfony\Component\Validator\Context\ExecutionContextInterface; final class AddressExistsValidatorSpec extends ObjectBehavior { - function let(ExecutionContextInterface $executionContext, AddressRepositoryInterface $addressRepository) - { - $this->beConstructedWith($addressRepository); + function let( + ExecutionContextInterface $executionContext, + AddressRepositoryInterface $addressRepository, + CurrentUserProviderInterface $currentUserProvider + ) { + $this->beConstructedWith($addressRepository, $currentUserProvider); $this->initialize($executionContext); } - function it_does_not_add_constraint_if_address_exists( + function it_does_not_add_constraint_if_address_exists_and_its_owned_by_current_user( AddressInterface $address, + ShopUserInterface $shopUser, + CustomerInterface $customerOwner, + CurrentUserProviderInterface $currentUserProvider, AddressRepositoryInterface $addressRepository, ExecutionContextInterface $executionContext ) { $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + $customerOwner->getEmail()->willReturn('oliver@queen.com'); + $address->getCustomer()->willReturn($customerOwner); + + $shopUser->getEmail()->willReturn('oliver@queen.com'); + $currentUserProvider->provide()->willReturn($shopUser); + $executionContext->addViolation(Argument::any(), Argument::any())->shouldNotBeCalled(); $this->validate('ADDRESS_ID', new AddressExists()); @@ -42,4 +57,26 @@ function it_adds_constraint_if_address_does_not_exits_exists( $this->validate('ADDRESS_ID', new AddressExists()); } + + function it_adds_constraint_if_current_user_is_not_address_owner( + AddressInterface $address, + AddressRepositoryInterface $addressRepository, + CurrentUserProviderInterface $currentUserProvider, + ShopUserInterface $shopUser, + CustomerInterface $customerOwner, + ExecutionContextInterface $executionContext + ) { + $addressRepository->findOneBy(['id' => 'ADDRESS_ID'])->willReturn($address); + + $customerOwner->getEmail()->willReturn('oliver@queen.com'); + $address->getCustomer()->willReturn($customerOwner); + + $currentUserProvider->provide()->willReturn($shopUser); + + $shopUser->getEmail()->willReturn('shop@example.com'); + + $executionContext->addViolation('sylius.shop_api.address.not_exists')->shouldBeCalled(); + + $this->validate('ADDRESS_ID', new AddressExists()); + } } diff --git a/src/Command/CreateAddress.php b/src/Command/CreateAddress.php index 3ac4a884f..804b0bd70 100644 --- a/src/Command/CreateAddress.php +++ b/src/Command/CreateAddress.php @@ -29,75 +29,11 @@ public function __construct(Address $address, string $userEmail) } /** - * @return string - */ - public function firstName(): string - { - return $this->address->firstName(); - } - - /** - * @return string - */ - public function lastName(): string - { - return $this->address->lastName(); - } - - /** - * @return string|null - */ - public function company(): ?string - { - return $this->address->company(); - } - - /** - * @return string - */ - public function street(): string - { - return $this->address->street(); - } - - /** - * @return string - */ - public function countryCode(): string - { - return $this->address->countryCode(); - } - - /** - * @return string|null - */ - public function provinceCode(): ?string - { - return $this->address->provinceCode(); - } - - /** - * @return string - */ - public function city(): string - { - return $this->address->city(); - } - - /** - * @return string - */ - public function postcode(): string - { - return $this->address->postcode(); - } - - /** - * @return string|null + * @return Address */ - public function phoneNumber(): ?string + public function address(): Address { - return $this->address->phoneNumber(); + return $this->address; } /** diff --git a/src/Command/RemoveAddress.php b/src/Command/RemoveAddress.php index bed9685c6..451c3aa90 100644 --- a/src/Command/RemoveAddress.php +++ b/src/Command/RemoveAddress.php @@ -4,7 +4,7 @@ namespace Sylius\ShopApiPlugin\Command; -class RemoveAddress +final class RemoveAddress { /** * @var mixed diff --git a/src/Controller/AddressBook/CreateAddressAction.php b/src/Controller/AddressBook/CreateAddressAction.php index c51a37b56..c9e9e1d9d 100644 --- a/src/Controller/AddressBook/CreateAddressAction.php +++ b/src/Controller/AddressBook/CreateAddressAction.php @@ -7,10 +7,10 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\ShopApiPlugin\Command\CreateAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; use Sylius\ShopApiPlugin\Model\Address; +use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; @@ -42,6 +42,10 @@ final class CreateAddressAction * @var TokenStorage */ private $tokenStorage; + /** + * @var CurrentUserProviderInterface + */ + private $currentUserProvider; /** * @param ViewHandlerInterface $viewHandler @@ -49,19 +53,22 @@ final class CreateAddressAction * @param ValidatorInterface $validator * @param ValidationErrorViewFactoryInterface $validationErrorViewFactory * @param TokenStorage $tokenStorage + * @param CurrentUserProviderInterface $currentUserProvider */ public function __construct( ViewHandlerInterface $viewHandler, CommandBus $bus, ValidatorInterface $validator, ValidationErrorViewFactoryInterface $validationErrorViewFactory, - TokenStorage $tokenStorage + TokenStorage $tokenStorage, + CurrentUserProviderInterface $currentUserProvider ) { $this->viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; $this->tokenStorage = $tokenStorage; + $this->currentUserProvider = $currentUserProvider; } /** @@ -79,10 +86,9 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - /** @var ShopUserInterface $shopUser */ - $shopUser = $this->tokenStorage->getToken()->getUser(); + $user = $this->currentUserProvider->provide(); - $this->bus->handle(new CreateAddress($addressModel, $shopUser->getEmail())); + $this->bus->handle(new CreateAddress($addressModel, $user->getEmail())); return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); } diff --git a/src/Controller/AddressBook/RemoveAddressAction.php b/src/Controller/AddressBook/RemoveAddressAction.php index 1b635a0fd..75cce757a 100644 --- a/src/Controller/AddressBook/RemoveAddressAction.php +++ b/src/Controller/AddressBook/RemoveAddressAction.php @@ -7,9 +7,9 @@ use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactory; +use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface; use Sylius\ShopApiPlugin\Request\RemoveAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -43,25 +43,33 @@ final class RemoveAddressAction */ private $tokenStorage; + /** + * @var CurrentUserProviderInterface + */ + private $currentUserProvider; + /** * @param ViewHandlerInterface $viewHandler * @param ValidatorInterface $validator * @param ValidationErrorViewFactory $validationErrorViewFactory * @param CommandBus $bus * @param TokenStorageInterface $tokenStorage + * @param CurrentUserProviderInterface $currentUserProvider */ public function __construct( ViewHandlerInterface $viewHandler, ValidatorInterface $validator, ValidationErrorViewFactory $validationErrorViewFactory, CommandBus $bus, - TokenStorageInterface $tokenStorage + TokenStorageInterface $tokenStorage, + CurrentUserProviderInterface $currentUserProvider ) { $this->viewHandler = $viewHandler; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; $this->bus = $bus; $this->tokenStorage = $tokenStorage; + $this->currentUserProvider = $currentUserProvider; } public function __invoke(Request $request): Response @@ -74,12 +82,11 @@ public function __invoke(Request $request): Response return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - /** @var ShopUserInterface $shopUser */ - $shopUser = $this->tokenStorage->getToken()->getUser(); + $user = $this->currentUserProvider->provide(); $this->bus->handle(new RemoveAddress( $request->attributes->get('id'), - $shopUser->getEmail() + $user->getEmail() )); return $this->viewHandler->handle(View::create('', Response::HTTP_NO_CONTENT)); diff --git a/src/Controller/AddressBook/SetDefaultAddressAction.php b/src/Controller/AddressBook/SetDefaultAddressAction.php index e79d7aa02..51bef7f56 100644 --- a/src/Controller/AddressBook/SetDefaultAddressAction.php +++ b/src/Controller/AddressBook/SetDefaultAddressAction.php @@ -9,6 +9,7 @@ use League\Tactician\CommandBus; use Sylius\ShopApiPlugin\Command\SetDefaultAddress; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; +use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface; use Sylius\ShopApiPlugin\Request\SetDefaultAddressRequest; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -41,6 +42,10 @@ final class SetDefaultAddressAction * @var TokenStorageInterface */ private $tokenStorage; + /** + * @var CurrentUserProviderInterface + */ + private $currentUserProvider; /** * @param ViewHandlerInterface $viewHandler @@ -48,19 +53,22 @@ final class SetDefaultAddressAction * @param ValidatorInterface $validator * @param ValidationErrorViewFactoryInterface $validationErrorViewFactory * @param TokenStorageInterface $tokenStorage + * @param CurrentUserProviderInterface $currentUserProvider */ public function __construct( ViewHandlerInterface $viewHandler, CommandBus $bus, ValidatorInterface $validator, ValidationErrorViewFactoryInterface $validationErrorViewFactory, - TokenStorageInterface $tokenStorage + TokenStorageInterface $tokenStorage, + CurrentUserProviderInterface $currentUserProvider ) { $this->viewHandler = $viewHandler; $this->bus = $bus; $this->validator = $validator; $this->validationErrorViewFactory = $validationErrorViewFactory; $this->tokenStorage = $tokenStorage; + $this->currentUserProvider = $currentUserProvider; } /** @@ -78,9 +86,11 @@ public function __invoke(Request $request) return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } + $user = $this->currentUserProvider->provide(); + $this->bus->handle(new SetDefaultAddress( $request->attributes->get('id'), - $this->tokenStorage->getToken()->getUser()->getEmail() + $user->getEmail() )); return $this->viewHandler->handle(View::create(null, Response::HTTP_NO_CONTENT)); diff --git a/src/Controller/AddressBook/UpdateAddressAction.php b/src/Controller/AddressBook/UpdateAddressAction.php index bbb1ace6d..af9c5caf4 100644 --- a/src/Controller/AddressBook/UpdateAddressAction.php +++ b/src/Controller/AddressBook/UpdateAddressAction.php @@ -8,12 +8,12 @@ use FOS\RestBundle\View\ViewHandlerInterface; use League\Tactician\CommandBus; use Sylius\Component\Core\Model\AddressInterface; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\ShopApiPlugin\Command\UpdateAddress; use Sylius\ShopApiPlugin\Factory\AddressBookViewFactoryInterface; use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface; use Sylius\ShopApiPlugin\Model\Address; +use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; @@ -55,6 +55,10 @@ final class UpdateAddressAction * @var TokenStorageInterface */ private $tokenStorage; + /** + * @var CurrentUserProviderInterface + */ + private $currentUserProvider; /** * @param ViewHandlerInterface $viewHandler @@ -64,6 +68,7 @@ final class UpdateAddressAction * @param AddressBookViewFactoryInterface $addressViewFactory * @param AddressRepositoryInterface $addressRepository * @param TokenStorageInterface $tokenStorage + * @param CurrentUserProviderInterface $currentUserProvider */ public function __construct( ViewHandlerInterface $viewHandler, @@ -72,7 +77,8 @@ public function __construct( ValidationErrorViewFactoryInterface $validationErrorViewFactory, AddressBookViewFactoryInterface $addressViewFactory, AddressRepositoryInterface $addressRepository, - TokenStorageInterface $tokenStorage + TokenStorageInterface $tokenStorage, + CurrentUserProviderInterface $currentUserProvider ) { $this->viewHandler = $viewHandler; $this->validator = $validator; @@ -81,6 +87,7 @@ public function __construct( $this->addressBookViewFactory = $addressViewFactory; $this->addressRepository = $addressRepository; $this->tokenStorage = $tokenStorage; + $this->currentUserProvider = $currentUserProvider; } public function __invoke(Request $request, $id): Response @@ -93,16 +100,15 @@ public function __invoke(Request $request, $id): Response return $this->viewHandler->handle(View::create($this->validationErrorViewFactory->create($validationResults), Response::HTTP_BAD_REQUEST)); } - /** @var ShopUserInterface $customer */ - $shopUser = $this->tokenStorage->getToken()->getUser(); + $user = $this->currentUserProvider->provide(); - $this->bus->handle(new UpdateAddress($addressModel, $shopUser->getEmail(), $id)); + $this->bus->handle(new UpdateAddress($addressModel, $user->getEmail(), $id)); /** @var AddressInterface $updatedAddress */ $updatedAddress = $this->addressRepository->findOneBy(['id' => $id]); return $this->viewHandler->handle(View::create( - $this->addressBookViewFactory->create($updatedAddress, $shopUser->getCustomer()), + $this->addressBookViewFactory->create($updatedAddress, $user->getCustomer()), Response::HTTP_OK) ); } diff --git a/src/Handler/CreateAddressHandler.php b/src/Handler/CreateAddressHandler.php index 1c0283f8d..18e7ce2de 100644 --- a/src/Handler/CreateAddressHandler.php +++ b/src/Handler/CreateAddressHandler.php @@ -65,22 +65,24 @@ public function handle(CreateAddress $command): void /** @var CustomerInterface $shopUser */ $customer = $this->customerRepository->findOneBy(['email' => $command->userEmail()]); + $addressData = $command->address(); + $this->assertCustomerExists($customer); - $this->assertCountryExists($command->countryCode()); + $this->assertCountryExists($addressData->countryCode()); /** @var AddressInterface $address */ $address = $this->addressFactory->createNew(); - $address->setFirstName($command->firstName()); - $address->setLastName($command->lastName()); - $address->setCompany($command->company()); - $address->setStreet($command->street()); - $address->setCountryCode($command->countryCode()); - $address->setCity($command->city()); - $address->setPostcode($command->postcode()); - $address->setPhoneNumber($command->phoneNumber()); - - if (null !== $command->provinceCode()) { - $province = $this->checkProvinceExists($command->provinceCode()); + $address->setFirstName($addressData->firstName()); + $address->setLastName($addressData->lastName()); + $address->setCompany($addressData->company()); + $address->setStreet($addressData->street()); + $address->setCountryCode($addressData->countryCode()); + $address->setCity($addressData->city()); + $address->setPostcode($addressData->postcode()); + $address->setPhoneNumber($addressData->phoneNumber()); + + if (null !== $addressData->provinceCode()) { + $province = $this->checkProvinceExists($addressData->provinceCode()); $address->setProvinceCode($province->getCode()); $address->setProvinceName($province->getName()); } @@ -93,7 +95,7 @@ public function handle(CreateAddress $command): void /** * @param $customer */ - private function assertCustomerExists($customer) + private function assertCustomerExists($customer): void { Assert::notNull($customer, 'Customer does not exists!'); } diff --git a/src/Handler/RemoveAddressHandler.php b/src/Handler/RemoveAddressHandler.php index a1ad67600..75262ed01 100644 --- a/src/Handler/RemoveAddressHandler.php +++ b/src/Handler/RemoveAddressHandler.php @@ -5,13 +5,9 @@ namespace Sylius\ShopApiPlugin\Handler; use Sylius\Component\Core\Model\AddressInterface; -use Sylius\Component\Core\Model\OrderInterface; -use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; -use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\ShopApiPlugin\Command\RemoveAddress; -use Webmozart\Assert\Assert; final class RemoveAddressHandler { @@ -25,48 +21,21 @@ final class RemoveAddressHandler */ private $orderRepository; - /** - * @var RepositoryInterface - */ - private $shopUserRepository; - /** * @param AddressRepositoryInterface $addressRepository * @param OrderRepositoryInterface $orderRepository - * @param RepositoryInterface $shopUserRepository */ - public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, RepositoryInterface $shopUserRepository) + public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository) { $this->addressRepository = $addressRepository; $this->orderRepository = $orderRepository; - $this->shopUserRepository = $shopUserRepository; } - public function handle(RemoveAddress $removeAddress) + public function handle(RemoveAddress $removeAddress): void { - /** @var ShopUserInterface $shopUser */ - $shopUser = $this->shopUserRepository->findOneBy(['username' => $removeAddress->userEmail()]); - /** @var AddressInterface $address */ $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id()]); - $this->assertCurrentUserIsOwner($address, $shopUser); - $this->assertOrderWithAddressNotExists($address); - $this->addressRepository->remove($address); } - - private function assertOrderWithAddressNotExists($address) - { - /** @var OrderInterface $orderShippingAddress */ - $orderShippingAddress = $this->orderRepository->findBy(['billingAddress' => $address]); - /** @var OrderInterface $orderBillingAddress */ - $orderBillingAddress = $this->orderRepository->findBy(['shippingAddress' => $address]); - Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders.'); - } - - private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) - { - Assert::eq($address->getCustomer()->getId(), $user->getId(), 'User is not owner of this address.'); - } } diff --git a/src/Model/Address.php b/src/Model/Address.php index 631531efa..cd9e14d63 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -100,7 +100,7 @@ private function __construct( * * @return Address */ - public static function createFromArray(array $address): Address + public static function createFromArray(array $address): self { Assert::keyExists($address, 'firstName'); Assert::keyExists($address, 'lastName'); @@ -128,7 +128,7 @@ public static function createFromArray(array $address): Address * * @return Address */ - public static function createFromRequest(Request $request): Address + public static function createFromRequest(Request $request): self { return new self( $request->request->get('firstName'), diff --git a/src/Provider/CurrentUserProvider.php b/src/Provider/CurrentUserProvider.php new file mode 100644 index 000000000..b76302a0a --- /dev/null +++ b/src/Provider/CurrentUserProvider.php @@ -0,0 +1,35 @@ +tokenStorage = $tokenStorage; + } + + /** + * @return ShopUserInterface + */ + public function provide(): ShopUserInterface + { + /** @var ShopUserInterface $user */ + $user = $this->tokenStorage->getToken()->getUser(); + + Assert::isInstanceOf($user, ShopUserInterface::class); + + return $user; + } +} diff --git a/src/Provider/CurrentUserProviderInterface.php b/src/Provider/CurrentUserProviderInterface.php new file mode 100644 index 000000000..2b553cda3 --- /dev/null +++ b/src/Provider/CurrentUserProviderInterface.php @@ -0,0 +1,12 @@ + + + + + diff --git a/src/Resources/config/services/actions/address_book.xml b/src/Resources/config/services/actions/address_book.xml index 2a7cce92e..5082a8e03 100644 --- a/src/Resources/config/services/actions/address_book.xml +++ b/src/Resources/config/services/actions/address_book.xml @@ -10,6 +10,7 @@ + + + + diff --git a/src/Resources/config/services/handlers.xml b/src/Resources/config/services/handlers.xml index 2ff51450f..9e2c72ec8 100644 --- a/src/Resources/config/services/handlers.xml +++ b/src/Resources/config/services/handlers.xml @@ -165,7 +165,6 @@ - diff --git a/src/Resources/config/services/validators.xml b/src/Resources/config/services/validators.xml index d1e9550a5..5ea7af388 100644 --- a/src/Resources/config/services/validators.xml +++ b/src/Resources/config/services/validators.xml @@ -74,6 +74,7 @@ class="Sylius\ShopApiPlugin\Validator\AddressExistsValidator" > + diff --git a/src/Validator/AddressExistsValidator.php b/src/Validator/AddressExistsValidator.php index 76e369f99..0f5bbcb25 100644 --- a/src/Validator/AddressExistsValidator.php +++ b/src/Validator/AddressExistsValidator.php @@ -4,7 +4,10 @@ namespace Sylius\ShopApiPlugin\Validator; +use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Repository\AddressRepositoryInterface; +use Sylius\ShopApiPlugin\Provider\CurrentUserProviderInterface; +use Sylius\ShopApiPlugin\Validator\Constraints\AddressExists; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; @@ -14,24 +17,41 @@ final class AddressExistsValidator extends ConstraintValidator * @var AddressRepositoryInterface */ private $addressRepository; + /** + * @var CurrentUserProviderInterface + */ + private $currentUserProvider; /** * AddressExistsValidator constructor. * * @param AddressRepositoryInterface $addressRepository + * @param CurrentUserProviderInterface $currentUserProvider */ - public function __construct(AddressRepositoryInterface $addressRepository) - { + public function __construct( + AddressRepositoryInterface $addressRepository, + CurrentUserProviderInterface $currentUserProvider + ) { $this->addressRepository = $addressRepository; + $this->currentUserProvider = $currentUserProvider; } /** - * {@inheritdoc} + * @param mixed $id + * @param Constraint|AddressExists $constraint */ public function validate($id, Constraint $constraint) { - if (null === $this->addressRepository->findOneBy(['id' => $id])) { - $this->context->addViolation($constraint->message); + $address = $this->addressRepository->findOneBy(['id' => $id]); + + if (!$address instanceof AddressInterface) { + return $this->context->addViolation($constraint->message); + } + + $user = $this->currentUserProvider->provide(); + + if ($address->getCustomer()->getEmail() !== $user->getEmail()) { + return $this->context->addViolation($constraint->message); } } } diff --git a/tests/Controller/AddressBookRemoveAddressApiTest.php b/tests/Controller/AddressBookRemoveAddressApiTest.php index d20a8d87b..08ecbe46c 100644 --- a/tests/Controller/AddressBookRemoveAddressApiTest.php +++ b/tests/Controller/AddressBookRemoveAddressApiTest.php @@ -75,6 +75,6 @@ public function it_validates_if_current_user_is_owner_of_address() $this->client->request('DELETE', sprintf('/shop-api/address-book/%s', $address->getId()), [], [], self::$acceptAndContentTypeHeader); $response = $this->client->getResponse(); - $this->assertResponseCode($response, Response::HTTP_INTERNAL_SERVER_ERROR); + $this->assertResponseCode($response, Response::HTTP_BAD_REQUEST); } } diff --git a/tests/DataFixtures/ORM/address.yml b/tests/DataFixtures/ORM/address.yml index 0fb1f5000..af4276e1a 100644 --- a/tests/DataFixtures/ORM/address.yml +++ b/tests/DataFixtures/ORM/address.yml @@ -42,4 +42,4 @@ Sylius\Component\Core\Model\Address: street: "Vukovarska" city: "Split" postcode: "21000" - customer: "@hater" \ No newline at end of file + customer: "@hater"