vendor/shopware/storefront/Controller/AddressController.php line 91

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Controller;
  3. use Shopware\Core\Checkout\Cart\Exception\CustomerNotLoggedInException;
  4. use Shopware\Core\Checkout\Cart\Order\Transformer\CustomerTransformer;
  5. use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressEntity;
  6. use Shopware\Core\Checkout\Customer\CustomerEntity;
  7. use Shopware\Core\Checkout\Customer\Exception\AddressNotFoundException;
  8. use Shopware\Core\Checkout\Customer\Exception\CannotDeleteDefaultAddressException;
  9. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractChangeCustomerProfileRoute;
  10. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractDeleteAddressRoute;
  11. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractListAddressRoute;
  12. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractUpsertAddressRoute;
  13. use Shopware\Core\Checkout\Customer\SalesChannel\AccountService;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  16. use Shopware\Core\Framework\Feature;
  17. use Shopware\Core\Framework\Routing\Annotation\LoginRequired;
  18. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  19. use Shopware\Core\Framework\Routing\Annotation\Since;
  20. use Shopware\Core\Framework\Routing\Exception\MissingRequestParameterException;
  21. use Shopware\Core\Framework\Uuid\Exception\InvalidUuidException;
  22. use Shopware\Core\Framework\Uuid\Uuid;
  23. use Shopware\Core\Framework\Validation\DataBag\DataBag;
  24. use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
  25. use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
  26. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  27. use Shopware\Storefront\Framework\Routing\Annotation\NoStore;
  28. use Shopware\Storefront\Page\Address\AddressEditorModalStruct;
  29. use Shopware\Storefront\Page\Address\Detail\AddressDetailPageLoadedHook;
  30. use Shopware\Storefront\Page\Address\Detail\AddressDetailPageLoader;
  31. use Shopware\Storefront\Page\Address\Listing\AddressBookWidgetLoadedHook;
  32. use Shopware\Storefront\Page\Address\Listing\AddressListingPageLoadedHook;
  33. use Shopware\Storefront\Page\Address\Listing\AddressListingPageLoader;
  34. use Symfony\Component\HttpFoundation\RedirectResponse;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpFoundation\Response;
  37. use Symfony\Component\Routing\Annotation\Route;
  38. /**
  39.  * @Route(defaults={"_routeScope"={"storefront"}})
  40.  *
  41.  * @deprecated tag:v6.5.0 - reason:becomes-internal - Will be internal
  42.  */
  43. class AddressController extends StorefrontController
  44. {
  45.     private const ADDRESS_TYPE_BILLING 'billing';
  46.     private const ADDRESS_TYPE_SHIPPING 'shipping';
  47.     private AccountService $accountService;
  48.     private AddressListingPageLoader $addressListingPageLoader;
  49.     private AddressDetailPageLoader $addressDetailPageLoader;
  50.     private AbstractListAddressRoute $listAddressRoute;
  51.     private AbstractUpsertAddressRoute $updateAddressRoute;
  52.     private AbstractDeleteAddressRoute $deleteAddressRoute;
  53.     private AbstractChangeCustomerProfileRoute $updateCustomerProfileRoute;
  54.     /**
  55.      * @internal
  56.      */
  57.     public function __construct(
  58.         AddressListingPageLoader $addressListingPageLoader,
  59.         AddressDetailPageLoader $addressDetailPageLoader,
  60.         AccountService $accountService,
  61.         AbstractListAddressRoute $listAddressRoute,
  62.         AbstractUpsertAddressRoute $updateAddressRoute,
  63.         AbstractDeleteAddressRoute $deleteAddressRoute,
  64.         AbstractChangeCustomerProfileRoute $updateCustomerProfileRoute
  65.     ) {
  66.         $this->accountService $accountService;
  67.         $this->addressListingPageLoader $addressListingPageLoader;
  68.         $this->addressDetailPageLoader $addressDetailPageLoader;
  69.         $this->listAddressRoute $listAddressRoute;
  70.         $this->updateAddressRoute $updateAddressRoute;
  71.         $this->deleteAddressRoute $deleteAddressRoute;
  72.         $this->updateCustomerProfileRoute $updateCustomerProfileRoute;
  73.     }
  74.     /**
  75.      * @Since("6.0.0.0")
  76.      * @Route("/account/address", name="frontend.account.address.page", options={"seo"="false"}, methods={"GET"}, defaults={"_loginRequired"=true})
  77.      * @NoStore
  78.      */
  79.     public function accountAddressOverview(Request $requestSalesChannelContext $contextCustomerEntity $customer): Response
  80.     {
  81.         $page $this->addressListingPageLoader->load($request$context$customer);
  82.         $this->hook(new AddressListingPageLoadedHook($page$context));
  83.         return $this->renderStorefront('@Storefront/storefront/page/account/addressbook/index.html.twig', ['page' => $page]);
  84.     }
  85.     /**
  86.      * @Since("6.0.0.0")
  87.      * @Route("/account/address/create", name="frontend.account.address.create.page", options={"seo"="false"}, methods={"GET"}, defaults={"_loginRequired"=true})
  88.      * @NoStore
  89.      */
  90.     public function accountCreateAddress(Request $requestRequestDataBag $dataSalesChannelContext $contextCustomerEntity $customer): Response
  91.     {
  92.         $page $this->addressDetailPageLoader->load($request$context$customer);
  93.         $this->hook(new AddressDetailPageLoadedHook($page$context));
  94.         return $this->renderStorefront('@Storefront/storefront/page/account/addressbook/create.html.twig', [
  95.             'page' => $page,
  96.             'data' => $data,
  97.         ]);
  98.     }
  99.     /**
  100.      * @Since("6.0.0.0")
  101.      * @Route("/account/address/{addressId}", name="frontend.account.address.edit.page", options={"seo"="false"}, methods={"GET"}, defaults={"_loginRequired"=true})
  102.      * @NoStore
  103.      */
  104.     public function accountEditAddress(Request $requestSalesChannelContext $contextCustomerEntity $customer): Response
  105.     {
  106.         $page $this->addressDetailPageLoader->load($request$context$customer);
  107.         $this->hook(new AddressDetailPageLoadedHook($page$context));
  108.         return $this->renderStorefront('@Storefront/storefront/page/account/addressbook/edit.html.twig', ['page' => $page]);
  109.     }
  110.     /**
  111.      * @Since("6.0.0.0")
  112.      * @Route("/account/address/default-{type}/{addressId}", name="frontend.account.address.set-default-address", methods={"POST"}, defaults={"_loginRequired"=true})
  113.      */
  114.     public function switchDefaultAddress(string $typestring $addressIdSalesChannelContext $contextCustomerEntity $customer): RedirectResponse
  115.     {
  116.         if (!Uuid::isValid($addressId)) {
  117.             throw new InvalidUuidException($addressId);
  118.         }
  119.         $success true;
  120.         try {
  121.             if ($type === self::ADDRESS_TYPE_SHIPPING) {
  122.                 $this->accountService->setDefaultShippingAddress($addressId$context$customer);
  123.             } elseif ($type === self::ADDRESS_TYPE_BILLING) {
  124.                 $this->accountService->setDefaultBillingAddress($addressId$context$customer);
  125.             } else {
  126.                 $success false;
  127.             }
  128.         } catch (AddressNotFoundException $exception) {
  129.             $success false;
  130.         }
  131.         return new RedirectResponse(
  132.             $this->generateUrl('frontend.account.address.page', ['changedDefaultAddress' => $success])
  133.         );
  134.     }
  135.     /**
  136.      * @Since("6.0.0.0")
  137.      * @Route("/account/address/delete/{addressId}", name="frontend.account.address.delete", options={"seo"="false"}, methods={"POST"}, defaults={"_loginRequired"=true})
  138.      */
  139.     public function deleteAddress(string $addressIdSalesChannelContext $contextCustomerEntity $customer): Response
  140.     {
  141.         $success true;
  142.         if (!$addressId) {
  143.             throw new MissingRequestParameterException('addressId');
  144.         }
  145.         try {
  146.             $this->deleteAddressRoute->delete($addressId$context$customer);
  147.         } catch (InvalidUuidException AddressNotFoundException CannotDeleteDefaultAddressException $exception) {
  148.             $success false;
  149.         }
  150.         return new RedirectResponse($this->generateUrl('frontend.account.address.page', ['addressDeleted' => $success]));
  151.     }
  152.     /**
  153.      * @Since("6.0.0.0")
  154.      * @Route("/account/address/create", name="frontend.account.address.create", options={"seo"="false"}, methods={"POST"}, defaults={"_loginRequired"=true})
  155.      * @Route("/account/address/{addressId}", name="frontend.account.address.edit.save", options={"seo"="false"}, methods={"POST"}, defaults={"_loginRequired"=true})
  156.      */
  157.     public function saveAddress(RequestDataBag $dataSalesChannelContext $contextCustomerEntity $customer): Response
  158.     {
  159.         /** @var RequestDataBag $address */
  160.         $address $data->get('address');
  161.         try {
  162.             $this->updateAddressRoute->upsert(
  163.                 $address->get('id'),
  164.                 $address->toRequestDataBag(),
  165.                 $context,
  166.                 $customer
  167.             );
  168.             return new RedirectResponse($this->generateUrl('frontend.account.address.page', ['addressSaved' => true]));
  169.         } catch (ConstraintViolationException $formViolations) {
  170.         }
  171.         if (!$address->get('id')) {
  172.             return $this->forwardToRoute('frontend.account.address.create.page', ['formViolations' => $formViolations]);
  173.         }
  174.         return $this->forwardToRoute(
  175.             'frontend.account.address.edit.page',
  176.             ['formViolations' => $formViolations],
  177.             ['addressId' => $address->get('id')]
  178.         );
  179.     }
  180.     /**
  181.      * @Since("6.0.0.0")
  182.      * @Route("/widgets/account/address-book", name="frontend.account.addressbook", options={"seo"=true}, methods={"POST"}, defaults={"XmlHttpRequest"=true, "_loginRequired"=true, "_loginRequiredAllowGuest"=true})
  183.      */
  184.     public function addressBook(Request $requestRequestDataBag $dataBagSalesChannelContext $contextCustomerEntity $customer): Response
  185.     {
  186.         $viewData = new AddressEditorModalStruct();
  187.         $this->handleChangeableAddresses($viewData$dataBag$context$customer);
  188.         $this->handleAddressCreation($viewData$dataBag$context$customer);
  189.         $this->handleAddressSelection($viewData$dataBag$context$customer);
  190.         $page $this->addressListingPageLoader->load($request$context$customer);
  191.         $this->hook(new AddressBookWidgetLoadedHook($page$context));
  192.         $viewData->setPage($page);
  193.         if (Feature::isActive('FEATURE_NEXT_15957')) {
  194.             $this->handleCustomerVatIds($dataBag$context$customer);
  195.         }
  196.         if ($request->get('redirectTo') || $request->get('forwardTo')) {
  197.             return $this->createActionResponse($request);
  198.         }
  199.         $response $this->renderStorefront(
  200.             '@Storefront/storefront/component/address/address-editor-modal.html.twig',
  201.             $viewData->getVars()
  202.         );
  203.         $response->headers->set('x-robots-tag''noindex');
  204.         return $response;
  205.     }
  206.     private function handleAddressCreation(
  207.         AddressEditorModalStruct $viewData,
  208.         RequestDataBag $dataBag,
  209.         SalesChannelContext $context,
  210.         CustomerEntity $customer
  211.     ): void {
  212.         /** @var DataBag|null $addressData */
  213.         $addressData $dataBag->get('address');
  214.         $addressId null;
  215.         if ($addressData === null) {
  216.             return;
  217.         }
  218.         try {
  219.             $response $this->updateAddressRoute->upsert(
  220.                 $addressData->get('id'),
  221.                 $addressData->toRequestDataBag(),
  222.                 $context,
  223.                 $customer
  224.             );
  225.             $addressId $response->getAddress()->getId();
  226.             $addressType null;
  227.             if ($viewData->isChangeBilling()) {
  228.                 $addressType self::ADDRESS_TYPE_BILLING;
  229.             } elseif ($viewData->isChangeShipping()) {
  230.                 $addressType self::ADDRESS_TYPE_SHIPPING;
  231.             }
  232.             // prepare data to set newly created address as customers default
  233.             if ($addressType) {
  234.                 $dataBag->set('selectAddress', new RequestDataBag([
  235.                     'id' => $addressId,
  236.                     'type' => $addressType,
  237.                 ]));
  238.             }
  239.             $success true;
  240.             $messages = ['type' => 'success''text' => $this->trans('account.addressSaved')];
  241.         } catch (\Exception $exception) {
  242.             $success false;
  243.             $messages = ['type' => 'danger''text' => $this->trans('error.message-default')];
  244.         }
  245.         $viewData->setAddressId($addressId);
  246.         $viewData->setSuccess($success);
  247.         $viewData->setMessages($messages);
  248.     }
  249.     private function handleChangeableAddresses(
  250.         AddressEditorModalStruct $viewData,
  251.         RequestDataBag $dataBag,
  252.         SalesChannelContext $context,
  253.         CustomerEntity $customer
  254.     ): void {
  255.         $changeableAddresses $dataBag->get('changeableAddresses');
  256.         if ($changeableAddresses === null) {
  257.             return;
  258.         }
  259.         $viewData->setChangeShipping((bool) $changeableAddresses->get('changeShipping'));
  260.         $viewData->setChangeBilling((bool) $changeableAddresses->get('changeBilling'));
  261.         $addressId $dataBag->get('id');
  262.         if (!$addressId) {
  263.             return;
  264.         }
  265.         $viewData->setAddress($this->getById($addressId$context$customer));
  266.     }
  267.     /**
  268.      * @throws CustomerNotLoggedInException
  269.      * @throws InvalidUuidException
  270.      */
  271.     private function handleAddressSelection(
  272.         AddressEditorModalStruct $viewData,
  273.         RequestDataBag $dataBag,
  274.         SalesChannelContext $context,
  275.         CustomerEntity $customer
  276.     ): void {
  277.         $selectedAddress $dataBag->get('selectAddress');
  278.         if ($selectedAddress === null) {
  279.             return;
  280.         }
  281.         $addressType $selectedAddress->get('type');
  282.         $addressId $selectedAddress->get('id');
  283.         if (!Uuid::isValid($addressId)) {
  284.             throw new InvalidUuidException($addressId);
  285.         }
  286.         $success true;
  287.         try {
  288.             if ($addressType === self::ADDRESS_TYPE_SHIPPING) {
  289.                 $address $this->getById($addressId$context$customer);
  290.                 $context->getCustomer()->setDefaultShippingAddress($address);
  291.                 $this->accountService->setDefaultShippingAddress($addressId$context$customer);
  292.             } elseif ($addressType === self::ADDRESS_TYPE_BILLING) {
  293.                 $address $this->getById($addressId$context$customer);
  294.                 $context->getCustomer()->setDefaultBillingAddress($address);
  295.                 $this->accountService->setDefaultBillingAddress($addressId$context$customer);
  296.             } else {
  297.                 $success false;
  298.             }
  299.         } catch (AddressNotFoundException $exception) {
  300.             $success false;
  301.         }
  302.         if ($success) {
  303.             $this->addFlash(self::SUCCESS$this->trans('account.addressDefaultChanged'));
  304.         } else {
  305.             $this->addFlash(self::DANGER$this->trans('account.addressDefaultNotChanged'));
  306.         }
  307.         $viewData->setSuccess($success);
  308.     }
  309.     private function getById(string $addressIdSalesChannelContext $contextCustomerEntity $customer): CustomerAddressEntity
  310.     {
  311.         if (!Uuid::isValid($addressId)) {
  312.             throw new InvalidUuidException($addressId);
  313.         }
  314.         $criteria = new Criteria();
  315.         $criteria->addFilter(new EqualsFilter('id'$addressId));
  316.         $criteria->addFilter(new EqualsFilter('customerId'$customer->getId()));
  317.         $address $this->listAddressRoute->load($criteria$context$customer)->getAddressCollection()->get($addressId);
  318.         if (!$address) {
  319.             throw new AddressNotFoundException($addressId);
  320.         }
  321.         return $address;
  322.     }
  323.     private function handleCustomerVatIds(RequestDataBag $dataBagSalesChannelContext $contextCustomerEntity $customer): void
  324.     {
  325.         if (!$dataBag->has('vatIds')) {
  326.             return;
  327.         }
  328.         $newVatIds $dataBag->get('vatIds')->all();
  329.         $oldVatIds $customer->getVatIds() ?? [];
  330.         if (!array_diff($newVatIds$oldVatIds) && !array_diff($oldVatIds$newVatIds)) {
  331.             return;
  332.         }
  333.         $dataCustomer CustomerTransformer::transform($customer);
  334.         $dataCustomer['vatIds'] = $newVatIds;
  335.         $dataCustomer['accountType'] = $customer->getCompany() === null CustomerEntity::ACCOUNT_TYPE_PRIVATE CustomerEntity::ACCOUNT_TYPE_BUSINESS;
  336.         $newDataBag = new RequestDataBag($dataCustomer);
  337.         $this->updateCustomerProfileRoute->change($newDataBag$context$customer);
  338.     }
  339. }