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.         $params = [];
  188.         try {
  189.             $this->handleChangeableAddresses($viewData$dataBag$context$customer);
  190.             $this->handleAddressCreation($viewData$dataBag$context$customer);
  191.             $this->handleAddressSelection($viewData$dataBag$context$customer);
  192.             $page $this->addressListingPageLoader->load($request$context$customer);
  193.             $this->hook(new AddressBookWidgetLoadedHook($page$context));
  194.             $viewData->setPage($page);
  195.             if (Feature::isActive('FEATURE_NEXT_15957')) {
  196.                 $this->handleCustomerVatIds($dataBag$context$customer);
  197.             }
  198.         } catch (ConstraintViolationException $formViolations) {
  199.             $params['formViolations'] = $formViolations;
  200.             $params['postedData'] = $dataBag->get('address');
  201.         } catch (\Exception $exception) {
  202.             $viewData->setSuccess(false);
  203.             $viewData->setMessages([
  204.                 'type' => self::DANGER,
  205.                 'text' => $this->trans('error.message-default'),
  206.             ]);
  207.         }
  208.         if ($request->get('redirectTo') || $request->get('forwardTo')) {
  209.             return $this->createActionResponse($request);
  210.         }
  211.         $params array_merge($params$viewData->getVars());
  212.         $response $this->renderStorefront(
  213.             '@Storefront/storefront/component/address/address-editor-modal.html.twig',
  214.             $params
  215.         );
  216.         $response->headers->set('x-robots-tag''noindex');
  217.         return $response;
  218.     }
  219.     private function handleAddressCreation(
  220.         AddressEditorModalStruct $viewData,
  221.         RequestDataBag $dataBag,
  222.         SalesChannelContext $context,
  223.         CustomerEntity $customer
  224.     ): void {
  225.         /** @var DataBag|null $addressData */
  226.         $addressData $dataBag->get('address');
  227.         if ($addressData === null) {
  228.             return;
  229.         }
  230.         $response $this->updateAddressRoute->upsert(
  231.             $addressData->get('id'),
  232.             $addressData->toRequestDataBag(),
  233.             $context,
  234.             $customer
  235.         );
  236.         $addressId $response->getAddress()->getId();
  237.         $addressType null;
  238.         if ($viewData->isChangeBilling()) {
  239.             $addressType self::ADDRESS_TYPE_BILLING;
  240.         } elseif ($viewData->isChangeShipping()) {
  241.             $addressType self::ADDRESS_TYPE_SHIPPING;
  242.         }
  243.         // prepare data to set newly created address as customers default
  244.         if ($addressType) {
  245.             $dataBag->set('selectAddress', new RequestDataBag([
  246.                 'id' => $addressId,
  247.                 'type' => $addressType,
  248.             ]));
  249.         }
  250.         $viewData->setAddressId($addressId);
  251.         $viewData->setSuccess(true);
  252.         $viewData->setMessages(['type' => 'success''text' => $this->trans('account.addressSaved')]);
  253.     }
  254.     private function handleChangeableAddresses(
  255.         AddressEditorModalStruct $viewData,
  256.         RequestDataBag $dataBag,
  257.         SalesChannelContext $context,
  258.         CustomerEntity $customer
  259.     ): void {
  260.         $changeableAddresses $dataBag->get('changeableAddresses');
  261.         if ($changeableAddresses === null) {
  262.             return;
  263.         }
  264.         $viewData->setChangeShipping((bool) $changeableAddresses->get('changeShipping'));
  265.         $viewData->setChangeBilling((bool) $changeableAddresses->get('changeBilling'));
  266.         $addressId $dataBag->get('id');
  267.         if (!$addressId) {
  268.             return;
  269.         }
  270.         $viewData->setAddress($this->getById($addressId$context$customer));
  271.     }
  272.     /**
  273.      * @throws CustomerNotLoggedInException
  274.      * @throws InvalidUuidException
  275.      */
  276.     private function handleAddressSelection(
  277.         AddressEditorModalStruct $viewData,
  278.         RequestDataBag $dataBag,
  279.         SalesChannelContext $context,
  280.         CustomerEntity $customer
  281.     ): void {
  282.         $selectedAddress $dataBag->get('selectAddress');
  283.         if ($selectedAddress === null) {
  284.             return;
  285.         }
  286.         $addressType $selectedAddress->get('type');
  287.         $addressId $selectedAddress->get('id');
  288.         if (!Uuid::isValid($addressId)) {
  289.             throw new InvalidUuidException($addressId);
  290.         }
  291.         $success true;
  292.         try {
  293.             if ($addressType === self::ADDRESS_TYPE_SHIPPING) {
  294.                 $address $this->getById($addressId$context$customer);
  295.                 $customer->setDefaultShippingAddress($address);
  296.                 $this->accountService->setDefaultShippingAddress($addressId$context$customer);
  297.             } elseif ($addressType === self::ADDRESS_TYPE_BILLING) {
  298.                 $address $this->getById($addressId$context$customer);
  299.                 $customer->setDefaultBillingAddress($address);
  300.                 $this->accountService->setDefaultBillingAddress($addressId$context$customer);
  301.             } else {
  302.                 $success false;
  303.             }
  304.         } catch (AddressNotFoundException $exception) {
  305.             $success false;
  306.         }
  307.         if ($success) {
  308.             $this->addFlash(self::SUCCESS$this->trans('account.addressDefaultChanged'));
  309.         } else {
  310.             $this->addFlash(self::DANGER$this->trans('account.addressDefaultNotChanged'));
  311.         }
  312.         $viewData->setSuccess($success);
  313.     }
  314.     private function getById(string $addressIdSalesChannelContext $contextCustomerEntity $customer): CustomerAddressEntity
  315.     {
  316.         if (!Uuid::isValid($addressId)) {
  317.             throw new InvalidUuidException($addressId);
  318.         }
  319.         $criteria = new Criteria();
  320.         $criteria->addFilter(new EqualsFilter('id'$addressId));
  321.         $criteria->addFilter(new EqualsFilter('customerId'$customer->getId()));
  322.         $address $this->listAddressRoute->load($criteria$context$customer)->getAddressCollection()->get($addressId);
  323.         if (!$address) {
  324.             throw new AddressNotFoundException($addressId);
  325.         }
  326.         return $address;
  327.     }
  328.     private function handleCustomerVatIds(RequestDataBag $dataBagSalesChannelContext $contextCustomerEntity $customer): void
  329.     {
  330.         if (!$dataBag->has('vatIds')) {
  331.             return;
  332.         }
  333.         $newVatIds $dataBag->get('vatIds')->all();
  334.         $oldVatIds $customer->getVatIds() ?? [];
  335.         if (!array_diff($newVatIds$oldVatIds) && !array_diff($oldVatIds$newVatIds)) {
  336.             return;
  337.         }
  338.         $dataCustomer CustomerTransformer::transform($customer);
  339.         $dataCustomer['vatIds'] = $newVatIds;
  340.         $dataCustomer['accountType'] = $customer->getCompany() === null CustomerEntity::ACCOUNT_TYPE_PRIVATE CustomerEntity::ACCOUNT_TYPE_BUSINESS;
  341.         $newDataBag = new RequestDataBag($dataCustomer);
  342.         $this->updateCustomerProfileRoute->change($newDataBag$context$customer);
  343.     }
  344. }