PageRenderTime 26ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/magento/module-customer/Controller/Adminhtml/Index/Save.php

https://gitlab.com/yousafsyed/easternglamor
PHP | 298 lines | 224 code | 21 blank | 53 comment | 28 complexity | 58a92d90452c56fad3d43e0caac11c8b MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright © 2016 Magento. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Controller\Adminhtml\Index;
  7. use Magento\Customer\Api\Data\CustomerInterface;
  8. use Magento\Customer\Controller\RegistryConstants;
  9. use Magento\Framework\Exception\LocalizedException;
  10. /**
  11. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  12. */
  13. class Save extends \Magento\Customer\Controller\Adminhtml\Index
  14. {
  15. /**
  16. * @var \Magento\Customer\Model\Metadata\FormFactory
  17. */
  18. protected $_formFactory;
  19. /**
  20. * Reformat customer account data to be compatible with customer service interface
  21. *
  22. * @return array
  23. */
  24. protected function _extractCustomerData()
  25. {
  26. $customerData = [];
  27. if ($this->getRequest()->getPost('customer')) {
  28. $serviceAttributes = [
  29. CustomerInterface::DEFAULT_BILLING,
  30. CustomerInterface::DEFAULT_SHIPPING,
  31. 'confirmation',
  32. 'sendemail_store_id',
  33. ];
  34. $customerData = $this->_extractData(
  35. $this->getRequest(),
  36. 'adminhtml_customer',
  37. \Magento\Customer\Api\CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
  38. $serviceAttributes,
  39. 'customer'
  40. );
  41. }
  42. if (isset($customerData['disable_auto_group_change'])) {
  43. $customerData['disable_auto_group_change'] = (int) filter_var(
  44. $customerData['disable_auto_group_change'],
  45. FILTER_VALIDATE_BOOLEAN
  46. );
  47. }
  48. return $customerData;
  49. }
  50. /**
  51. * Perform customer data filtration based on form code and form object
  52. *
  53. * @param \Magento\Framework\App\RequestInterface $request
  54. * @param string $formCode The code of EAV form to take the list of attributes from
  55. * @param string $entityType entity type for the form
  56. * @param string[] $additionalAttributes The list of attribute codes to skip filtration for
  57. * @param string $scope scope of the request
  58. * @param \Magento\Customer\Model\Metadata\Form $metadataForm to use for extraction
  59. * @return array Filtered customer data
  60. */
  61. protected function _extractData(
  62. \Magento\Framework\App\RequestInterface $request,
  63. $formCode,
  64. $entityType,
  65. $additionalAttributes = [],
  66. $scope = null,
  67. \Magento\Customer\Model\Metadata\Form $metadataForm = null
  68. ) {
  69. if ($metadataForm === null) {
  70. $metadataForm = $this->_formFactory->create(
  71. $entityType,
  72. $formCode,
  73. [],
  74. false,
  75. \Magento\Customer\Model\Metadata\Form::DONT_IGNORE_INVISIBLE
  76. );
  77. }
  78. $filteredData = $metadataForm->extractData($request, $scope);
  79. $object = $this->_objectFactory->create(['data' => $request->getPostValue()]);
  80. $requestData = $object->getData($scope);
  81. foreach ($additionalAttributes as $attributeCode) {
  82. $filteredData[$attributeCode] = isset($requestData[$attributeCode]) ? $requestData[$attributeCode] : false;
  83. }
  84. $formAttributes = $metadataForm->getAttributes();
  85. /** @var \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute */
  86. foreach ($formAttributes as $attribute) {
  87. $attributeCode = $attribute->getAttributeCode();
  88. $frontendInput = $attribute->getFrontendInput();
  89. if ($frontendInput != 'boolean' && $filteredData[$attributeCode] === false) {
  90. unset($filteredData[$attributeCode]);
  91. }
  92. }
  93. return $filteredData;
  94. }
  95. /**
  96. * Saves default_billing and default_shipping flags for customer address
  97. *
  98. * @param array $addressIdList
  99. * @param array $extractedCustomerData
  100. * @return array
  101. */
  102. protected function saveDefaultFlags(array $addressIdList, array & $extractedCustomerData)
  103. {
  104. $result = [];
  105. $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = null;
  106. $extractedCustomerData[CustomerInterface::DEFAULT_SHIPPING] = null;
  107. foreach ($addressIdList as $addressId) {
  108. $scope = sprintf('address/%s', $addressId);
  109. $addressData = $this->_extractData(
  110. $this->getRequest(),
  111. 'adminhtml_customer_address',
  112. \Magento\Customer\Api\AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
  113. ['default_billing', 'default_shipping'],
  114. $scope
  115. );
  116. if (is_numeric($addressId)) {
  117. $addressData['id'] = $addressId;
  118. }
  119. // Set default billing and shipping flags to customer
  120. if (!empty($addressData['default_billing']) && $addressData['default_billing'] === 'true') {
  121. $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = $addressId;
  122. $addressData['default_billing'] = true;
  123. } else {
  124. $addressData['default_billing'] = false;
  125. }
  126. if (!empty($addressData['default_shipping']) && $addressData['default_shipping'] === 'true') {
  127. $extractedCustomerData[CustomerInterface::DEFAULT_SHIPPING] = $addressId;
  128. $addressData['default_shipping'] = true;
  129. } else {
  130. $addressData['default_shipping'] = false;
  131. }
  132. $result[] = $addressData;
  133. }
  134. return $result;
  135. }
  136. /**
  137. * Reformat customer addresses data to be compatible with customer service interface
  138. *
  139. * @param array $extractedCustomerData
  140. * @return array
  141. */
  142. protected function _extractCustomerAddressData(array & $extractedCustomerData)
  143. {
  144. $addresses = $this->getRequest()->getPost('address');
  145. $result = [];
  146. if (is_array($addresses)) {
  147. if (isset($addresses['_template_'])) {
  148. unset($addresses['_template_']);
  149. }
  150. $addressIdList = array_keys($addresses);
  151. $result = $this->saveDefaultFlags($addressIdList, $extractedCustomerData);
  152. }
  153. return $result;
  154. }
  155. /**
  156. * Save customer action
  157. *
  158. * @return \Magento\Backend\Model\View\Result\Redirect
  159. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  160. * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  161. * @SuppressWarnings(PHPMD.NPathComplexity)
  162. */
  163. public function execute()
  164. {
  165. $returnToEdit = false;
  166. $originalRequestData = $this->getRequest()->getPostValue();
  167. $customerId = isset($originalRequestData['customer']['entity_id'])
  168. ? $originalRequestData['customer']['entity_id']
  169. : null;
  170. if ($originalRequestData) {
  171. try {
  172. // optional fields might be set in request for future processing by observers in other modules
  173. $customerData = $this->_extractCustomerData();
  174. $addressesData = $this->_extractCustomerAddressData($customerData);
  175. $request = $this->getRequest();
  176. $isExistingCustomer = (bool)$customerId;
  177. $customer = $this->customerDataFactory->create();
  178. if ($isExistingCustomer) {
  179. $savedCustomerData = $this->_customerRepository->getById($customerId);
  180. $customerData = array_merge(
  181. $this->customerMapper->toFlatArray($savedCustomerData),
  182. $customerData
  183. );
  184. $customerData['id'] = $customerId;
  185. }
  186. $this->dataObjectHelper->populateWithArray(
  187. $customer,
  188. $customerData,
  189. '\Magento\Customer\Api\Data\CustomerInterface'
  190. );
  191. $addresses = [];
  192. foreach ($addressesData as $addressData) {
  193. $region = isset($addressData['region']) ? $addressData['region'] : null;
  194. $regionId = isset($addressData['region_id']) ? $addressData['region_id'] : null;
  195. $addressData['region'] = [
  196. 'region' => $region,
  197. 'region_id' => $regionId,
  198. ];
  199. $addressDataObject = $this->addressDataFactory->create();
  200. $this->dataObjectHelper->populateWithArray(
  201. $addressDataObject,
  202. $addressData,
  203. '\Magento\Customer\Api\Data\AddressInterface'
  204. );
  205. $addresses[] = $addressDataObject;
  206. }
  207. $this->_eventManager->dispatch(
  208. 'adminhtml_customer_prepare_save',
  209. ['customer' => $customer, 'request' => $request]
  210. );
  211. $customer->setAddresses($addresses);
  212. $customer->setStoreId($customerData['sendemail_store_id']);
  213. // Save customer
  214. if ($isExistingCustomer) {
  215. $this->_customerRepository->save($customer);
  216. } else {
  217. $customer = $this->customerAccountManagement->createAccount($customer);
  218. $customerId = $customer->getId();
  219. }
  220. $isSubscribed = null;
  221. if ($this->_authorization->isAllowed(null)) {
  222. $isSubscribed = $this->getRequest()->getPost('subscription');
  223. }
  224. if ($isSubscribed !== null) {
  225. if ($isSubscribed !== 'false') {
  226. $this->_subscriberFactory->create()->subscribeCustomerById($customerId);
  227. } else {
  228. $this->_subscriberFactory->create()->unsubscribeCustomerById($customerId);
  229. }
  230. }
  231. // After save
  232. $this->_eventManager->dispatch(
  233. 'adminhtml_customer_save_after',
  234. ['customer' => $customer, 'request' => $request]
  235. );
  236. $this->_getSession()->unsCustomerData();
  237. // Done Saving customer, finish save action
  238. $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
  239. $this->messageManager->addSuccess(__('You saved the customer.'));
  240. $returnToEdit = (bool)$this->getRequest()->getParam('back', false);
  241. } catch (\Magento\Framework\Validator\Exception $exception) {
  242. $messages = $exception->getMessages();
  243. if (empty($messages)) {
  244. $messages = $exception->getMessage();
  245. }
  246. $this->_addSessionErrorMessages($messages);
  247. $this->_getSession()->setCustomerData($originalRequestData);
  248. $returnToEdit = true;
  249. } catch (LocalizedException $exception) {
  250. $this->_addSessionErrorMessages($exception->getMessage());
  251. $this->_getSession()->setCustomerData($originalRequestData);
  252. $returnToEdit = true;
  253. } catch (\Exception $exception) {
  254. $this->messageManager->addException($exception, __('Something went wrong while saving the customer.'));
  255. $this->_getSession()->setCustomerData($originalRequestData);
  256. $returnToEdit = true;
  257. }
  258. }
  259. $resultRedirect = $this->resultRedirectFactory->create();
  260. if ($returnToEdit) {
  261. if ($customerId) {
  262. $resultRedirect->setPath(
  263. 'customer/*/edit',
  264. ['id' => $customerId, '_current' => true]
  265. );
  266. } else {
  267. $resultRedirect->setPath(
  268. 'customer/*/new',
  269. ['_current' => true]
  270. );
  271. }
  272. } else {
  273. $resultRedirect->setPath('customer/index');
  274. }
  275. return $resultRedirect;
  276. }
  277. }