|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | + |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace Magento\Customer\Model\Plugin; |
| 10 | + |
| 11 | +use Magento\Framework\Webapi\Rest\Request as RestRequest; |
| 12 | +use Magento\Customer\Api\Data\CustomerInterface; |
| 13 | +use Magento\Customer\Api\CustomerRepositoryInterface; |
| 14 | + |
| 15 | +/** |
| 16 | + * Update customer by id from request param |
| 17 | + */ |
| 18 | +class UpdateCustomer |
| 19 | +{ |
| 20 | + /** |
| 21 | + * @var RestRequest |
| 22 | + */ |
| 23 | + private $request; |
| 24 | + |
| 25 | + /** |
| 26 | + * @param RestRequest $request |
| 27 | + */ |
| 28 | + public function __construct(RestRequest $request) |
| 29 | + { |
| 30 | + $this->request = $request; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Update customer by id from request if exist |
| 35 | + * |
| 36 | + * @param CustomerRepositoryInterface $customerRepository |
| 37 | + * @param CustomerInterface $customer |
| 38 | + * @param string|null $passwordHash |
| 39 | + * @return array |
| 40 | + */ |
| 41 | + public function beforeSave( |
| 42 | + CustomerRepositoryInterface $customerRepository, |
| 43 | + CustomerInterface $customer, |
| 44 | + ?string $passwordHash = null |
| 45 | + ): array { |
| 46 | + $customerId = $this->request->getParam('customerId'); |
| 47 | + |
| 48 | + if ($customerId) { |
| 49 | + $customer = $this->getUpdatedCustomer($customerRepository->getById($customerId), $customer); |
| 50 | + } |
| 51 | + |
| 52 | + return [$customer, $passwordHash]; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Return updated customer |
| 57 | + * |
| 58 | + * @param CustomerInterface $originCustomer |
| 59 | + * @param CustomerInterface $customer |
| 60 | + * @return CustomerInterface |
| 61 | + */ |
| 62 | + private function getUpdatedCustomer( |
| 63 | + CustomerInterface $originCustomer, |
| 64 | + CustomerInterface $customer |
| 65 | + ): CustomerInterface { |
| 66 | + $newCustomer = clone $originCustomer; |
| 67 | + foreach ($customer->__toArray() as $name => $value) { |
| 68 | + if ($name === CustomerInterface::CUSTOM_ATTRIBUTES) { |
| 69 | + $value = $customer->getCustomAttributes(); |
| 70 | + } elseif ($name === CustomerInterface::EXTENSION_ATTRIBUTES_KEY) { |
| 71 | + $value = $customer->getExtensionAttributes(); |
| 72 | + } elseif ($name === CustomerInterface::KEY_ADDRESSES) { |
| 73 | + $value = $customer->getAddresses(); |
| 74 | + } |
| 75 | + |
| 76 | + $newCustomer->setData($name, $value); |
| 77 | + } |
| 78 | + |
| 79 | + return $newCustomer; |
| 80 | + } |
| 81 | +} |
0 commit comments