FormPost.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Controller\Address;
  7. use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
  8. use Magento\Customer\Api\AddressRepositoryInterface;
  9. use Magento\Customer\Api\Data\AddressInterfaceFactory;
  10. use Magento\Customer\Api\Data\RegionInterface;
  11. use Magento\Customer\Api\Data\RegionInterfaceFactory;
  12. use Magento\Customer\Model\Address\Mapper;
  13. use Magento\Customer\Model\Metadata\FormFactory;
  14. use Magento\Customer\Model\Session;
  15. use Magento\Directory\Helper\Data as HelperData;
  16. use Magento\Directory\Model\RegionFactory;
  17. use Magento\Framework\Api\DataObjectHelper;
  18. use Magento\Framework\App\Action\Context;
  19. use Magento\Framework\App\ObjectManager;
  20. use Magento\Framework\Controller\Result\ForwardFactory;
  21. use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
  22. use Magento\Framework\Exception\InputException;
  23. use Magento\Framework\Reflection\DataObjectProcessor;
  24. use Magento\Framework\View\Result\PageFactory;
  25. /**
  26. * Customer Address Form Post Controller
  27. *
  28. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  29. */
  30. class FormPost extends \Magento\Customer\Controller\Address implements HttpPostActionInterface
  31. {
  32. /**
  33. * @var RegionFactory
  34. */
  35. protected $regionFactory;
  36. /**
  37. * @var HelperData
  38. */
  39. protected $helperData;
  40. /**
  41. * @var Mapper
  42. */
  43. private $customerAddressMapper;
  44. /**
  45. * @param Context $context
  46. * @param Session $customerSession
  47. * @param FormKeyValidator $formKeyValidator
  48. * @param FormFactory $formFactory
  49. * @param AddressRepositoryInterface $addressRepository
  50. * @param AddressInterfaceFactory $addressDataFactory
  51. * @param RegionInterfaceFactory $regionDataFactory
  52. * @param DataObjectProcessor $dataProcessor
  53. * @param DataObjectHelper $dataObjectHelper
  54. * @param ForwardFactory $resultForwardFactory
  55. * @param PageFactory $resultPageFactory
  56. * @param RegionFactory $regionFactory
  57. * @param HelperData $helperData
  58. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  59. */
  60. public function __construct(
  61. Context $context,
  62. Session $customerSession,
  63. FormKeyValidator $formKeyValidator,
  64. FormFactory $formFactory,
  65. AddressRepositoryInterface $addressRepository,
  66. AddressInterfaceFactory $addressDataFactory,
  67. RegionInterfaceFactory $regionDataFactory,
  68. DataObjectProcessor $dataProcessor,
  69. DataObjectHelper $dataObjectHelper,
  70. ForwardFactory $resultForwardFactory,
  71. PageFactory $resultPageFactory,
  72. RegionFactory $regionFactory,
  73. HelperData $helperData
  74. ) {
  75. $this->regionFactory = $regionFactory;
  76. $this->helperData = $helperData;
  77. parent::__construct(
  78. $context,
  79. $customerSession,
  80. $formKeyValidator,
  81. $formFactory,
  82. $addressRepository,
  83. $addressDataFactory,
  84. $regionDataFactory,
  85. $dataProcessor,
  86. $dataObjectHelper,
  87. $resultForwardFactory,
  88. $resultPageFactory
  89. );
  90. }
  91. /**
  92. * Extract address from request
  93. *
  94. * @return \Magento\Customer\Api\Data\AddressInterface
  95. */
  96. protected function _extractAddress()
  97. {
  98. $existingAddressData = $this->getExistingAddressData();
  99. /** @var \Magento\Customer\Model\Metadata\Form $addressForm */
  100. $addressForm = $this->_formFactory->create(
  101. 'customer_address',
  102. 'customer_address_edit',
  103. $existingAddressData
  104. );
  105. $addressData = $addressForm->extractData($this->getRequest());
  106. $attributeValues = $addressForm->compactData($addressData);
  107. $this->updateRegionData($attributeValues);
  108. $addressDataObject = $this->addressDataFactory->create();
  109. $this->dataObjectHelper->populateWithArray(
  110. $addressDataObject,
  111. array_merge($existingAddressData, $attributeValues),
  112. \Magento\Customer\Api\Data\AddressInterface::class
  113. );
  114. $addressDataObject->setCustomerId($this->_getSession()->getCustomerId())
  115. ->setIsDefaultBilling(
  116. $this->getRequest()->getParam(
  117. 'default_billing',
  118. isset($existingAddressData['default_billing']) ? $existingAddressData['default_billing'] : false
  119. )
  120. )
  121. ->setIsDefaultShipping(
  122. $this->getRequest()->getParam(
  123. 'default_shipping',
  124. isset($existingAddressData['default_shipping']) ? $existingAddressData['default_shipping'] : false
  125. )
  126. );
  127. return $addressDataObject;
  128. }
  129. /**
  130. * Retrieve existing address data
  131. *
  132. * @return array
  133. * @throws \Exception
  134. */
  135. protected function getExistingAddressData()
  136. {
  137. $existingAddressData = [];
  138. if ($addressId = $this->getRequest()->getParam('id')) {
  139. $existingAddress = $this->_addressRepository->getById($addressId);
  140. if ($existingAddress->getCustomerId() !== $this->_getSession()->getCustomerId()) {
  141. throw new \Exception();
  142. }
  143. $existingAddressData = $this->getCustomerAddressMapper()->toFlatArray($existingAddress);
  144. }
  145. return $existingAddressData;
  146. }
  147. /**
  148. * Update region data
  149. *
  150. * @param array $attributeValues
  151. * @return void
  152. * @SuppressWarnings(PHPMD.NPathComplexity)
  153. */
  154. protected function updateRegionData(&$attributeValues)
  155. {
  156. if (!empty($attributeValues['region_id'])) {
  157. $newRegion = $this->regionFactory->create()->load($attributeValues['region_id']);
  158. $attributeValues['region_code'] = $newRegion->getCode();
  159. $attributeValues['region'] = $newRegion->getDefaultName();
  160. }
  161. $regionData = [
  162. RegionInterface::REGION_ID => !empty($attributeValues['region_id']) ? $attributeValues['region_id'] : null,
  163. RegionInterface::REGION => !empty($attributeValues['region']) ? $attributeValues['region'] : null,
  164. RegionInterface::REGION_CODE => !empty($attributeValues['region_code'])
  165. ? $attributeValues['region_code']
  166. : null,
  167. ];
  168. $region = $this->regionDataFactory->create();
  169. $this->dataObjectHelper->populateWithArray(
  170. $region,
  171. $regionData,
  172. \Magento\Customer\Api\Data\RegionInterface::class
  173. );
  174. $attributeValues['region'] = $region;
  175. }
  176. /**
  177. * Process address form save
  178. *
  179. * @return \Magento\Framework\Controller\Result\Redirect
  180. */
  181. public function execute()
  182. {
  183. $redirectUrl = null;
  184. if (!$this->_formKeyValidator->validate($this->getRequest())) {
  185. return $this->resultRedirectFactory->create()->setPath('*/*/');
  186. }
  187. if (!$this->getRequest()->isPost()) {
  188. $this->_getSession()->setAddressFormData($this->getRequest()->getPostValue());
  189. return $this->resultRedirectFactory->create()->setUrl(
  190. $this->_redirect->error($this->_buildUrl('*/*/edit'))
  191. );
  192. }
  193. try {
  194. $address = $this->_extractAddress();
  195. $this->_addressRepository->save($address);
  196. $this->messageManager->addSuccessMessage(__('You saved the address.'));
  197. $url = $this->_buildUrl('*/*/index', ['_secure' => true]);
  198. return $this->resultRedirectFactory->create()->setUrl($this->_redirect->success($url));
  199. } catch (InputException $e) {
  200. $this->messageManager->addErrorMessage($e->getMessage());
  201. foreach ($e->getErrors() as $error) {
  202. $this->messageManager->addErrorMessage($error->getMessage());
  203. }
  204. } catch (\Exception $e) {
  205. $redirectUrl = $this->_buildUrl('*/*/index');
  206. $this->messageManager->addExceptionMessage($e, __('We can\'t save the address.'));
  207. }
  208. $url = $redirectUrl;
  209. if (!$redirectUrl) {
  210. $this->_getSession()->setAddressFormData($this->getRequest()->getPostValue());
  211. $url = $this->_buildUrl('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
  212. }
  213. return $this->resultRedirectFactory->create()->setUrl($this->_redirect->error($url));
  214. }
  215. /**
  216. * Get Customer Address Mapper instance
  217. *
  218. * @return Mapper
  219. *
  220. * @deprecated 100.1.3
  221. */
  222. private function getCustomerAddressMapper()
  223. {
  224. if ($this->customerAddressMapper === null) {
  225. $this->customerAddressMapper = ObjectManager::getInstance()->get(
  226. \Magento\Customer\Model\Address\Mapper::class
  227. );
  228. }
  229. return $this->customerAddressMapper;
  230. }
  231. }