CustomerProfileProcessor.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace Webkul\BagistoApi\State;
  3. use ApiPlatform\Metadata\Operation;
  4. use ApiPlatform\State\ProcessorInterface;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Event;
  7. use Illuminate\Support\Facades\Hash;
  8. use Illuminate\Support\Facades\Request;
  9. use Illuminate\Support\Facades\Storage;
  10. use Webkul\BagistoApi\Dto\CustomerProfileOutput;
  11. use Webkul\BagistoApi\Exception\AuthenticationException;
  12. use Webkul\BagistoApi\Exception\InvalidInputException;
  13. use Webkul\BagistoApi\Helper\CustomerProfileHelper;
  14. use Webkul\BagistoApi\Models\CustomerProfile as CustomerProfileModel;
  15. use Webkul\BagistoApi\Validators\CustomerValidator;
  16. use Webkul\Customer\Models\Customer;
  17. class CustomerProfileProcessor implements ProcessorInterface
  18. {
  19. public function __construct(
  20. protected CustomerValidator $validator
  21. ) {}
  22. public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
  23. {
  24. // For GraphQL mutations, always prefer context args input as it's the source of truth
  25. // The denormalized object may not have all fields properly populated
  26. if (isset($context['args']['input']) && is_array($context['args']['input'])) {
  27. $inputData = $context['args']['input'];
  28. // Merge with existing data, preferring args values
  29. if (is_object($data)) {
  30. $dataArray = (array) $data;
  31. $data = (object) array_merge($dataArray, $inputData);
  32. } else {
  33. $data = (object) $inputData;
  34. }
  35. }
  36. $request = Request::instance() ?? ($context['request'] ?? null);
  37. if (! $request) {
  38. throw new AuthenticationException(__('bagistoapi::app.graphql.auth.request-not-found'));
  39. }
  40. $token = null;
  41. if (is_object($data) && property_exists($data, 'token')) {
  42. $token = $data->token;
  43. }
  44. if (! $token) {
  45. $token = $this->extractToken($request);
  46. }
  47. if (! $token) {
  48. throw new AuthenticationException(__('bagistoapi::app.graphql.auth.token-required'));
  49. }
  50. $authenticatedCustomer = $this->getCustomerFromToken($token);
  51. if (! $authenticatedCustomer) {
  52. throw new AuthenticationException(__('bagistoapi::app.graphql.auth.invalid-or-expired-token'));
  53. }
  54. $resourceClass = $operation->getClass();
  55. $resourceShortName = class_basename($resourceClass);
  56. if ($resourceShortName === 'CustomerProfileDelete') {
  57. return $this->handleDelete($authenticatedCustomer);
  58. } elseif ($resourceShortName === 'CustomerProfileUpdate') {
  59. return $this->handleUpdate($data, $authenticatedCustomer);
  60. } elseif ($resourceShortName === 'CustomerProfile') {
  61. return $this->mapCustomerToProfile($authenticatedCustomer);
  62. }
  63. throw new \InvalidArgumentException(__('bagistoapi::app.graphql.auth.unknown-resource'));
  64. }
  65. /**
  66. * Map customer model to DTO object
  67. */
  68. private function mapCustomerToProfile(Customer $authenticatedCustomer): CustomerProfileModel
  69. {
  70. return CustomerProfileHelper::mapCustomerToProfile($authenticatedCustomer);
  71. }
  72. /**
  73. * Handle customer profile update.
  74. */
  75. private function handleUpdate(mixed $data, Customer $authenticatedCustomer): CustomerProfileOutput
  76. {
  77. $updateData = [];
  78. if (is_object($data) && property_exists($data, 'id') && $data->id) {
  79. if ((int) $data->id !== (int) $authenticatedCustomer->id) {
  80. throw new AuthenticationException(__('bagistoapi::app.graphql.auth.cannot-update-other-profile'));
  81. }
  82. }
  83. if (is_object($data) && property_exists($data, 'firstName') && ! empty($data->firstName)) {
  84. $updateData['first_name'] = $data->firstName;
  85. }
  86. if (is_object($data) && property_exists($data, 'lastName') && ! empty($data->lastName)) {
  87. $updateData['last_name'] = $data->lastName;
  88. }
  89. if (is_object($data) && property_exists($data, 'email') && ! empty($data->email)) {
  90. $updateData['email'] = $data->email;
  91. }
  92. if (is_object($data) && property_exists($data, 'phone') && ! empty($data->phone)) {
  93. // Validate phone - no special characters allowed
  94. $this->validatePhone($data->phone);
  95. $updateData['phone'] = $data->phone;
  96. }
  97. if (is_object($data) && property_exists($data, 'gender') && ! empty($data->gender)) {
  98. // Validate and normalize gender
  99. $updateData['gender'] = $this->validator->validateGender($data->gender);
  100. }
  101. if (is_object($data) && property_exists($data, 'dateOfBirth') && ! empty($data->dateOfBirth)) {
  102. $updateData['date_of_birth'] = $data->dateOfBirth;
  103. }
  104. if (is_object($data) && property_exists($data, 'password') && ! empty($data->password)) {
  105. if (is_object($data) && property_exists($data, 'confirmPassword')) {
  106. if ($data->password !== $data->confirmPassword) {
  107. throw new \InvalidArgumentException(__('bagistoapi::app.graphql.customer.password-mismatch'));
  108. }
  109. }
  110. if (! Hash::isHashed($data->password)) {
  111. $updateData['password'] = Hash::make($data->password);
  112. }
  113. }
  114. if (is_object($data) && property_exists($data, 'subscribedToNewsLetter')) {
  115. $updateData['subscribed_to_news_letter'] = $data->subscribedToNewsLetter;
  116. }
  117. if (is_object($data) && property_exists($data, 'status') && ! empty($data->status)) {
  118. $updateData['status'] = $data->status;
  119. }
  120. if (is_object($data) && property_exists($data, 'isVerified') && ! empty($data->isVerified)) {
  121. $updateData['is_verified'] = $data->isVerified;
  122. }
  123. if (is_object($data) && property_exists($data, 'isSuspended') && ! empty($data->isSuspended)) {
  124. $updateData['is_suspended'] = $data->isSuspended;
  125. }
  126. Event::dispatch('customer.update.before');
  127. if (! empty($updateData)) {
  128. $authenticatedCustomer->update($updateData);
  129. }
  130. if (is_object($data) && property_exists($data, 'deleteImage') && $data->deleteImage) {
  131. if ($authenticatedCustomer->image) {
  132. Storage::delete($authenticatedCustomer->image);
  133. $authenticatedCustomer->update(['image' => null]);
  134. }
  135. } elseif (is_object($data) && property_exists($data, 'image') && ! empty($data->image)) {
  136. $this->handleImageUpload($data->image, $authenticatedCustomer);
  137. }
  138. $authenticatedCustomer->refresh();
  139. Event::dispatch('customer.update.after', $authenticatedCustomer);
  140. $output = CustomerProfileHelper::mapCustomerToProfileOutput($authenticatedCustomer);
  141. $output->success = true;
  142. $output->message = __('bagistoapi::app.graphql.customer-profile.profile-updated');
  143. return $output;
  144. }
  145. /**
  146. * Handle customer profile deletion.
  147. */
  148. private function handleDelete(Customer $authenticatedCustomer): null
  149. {
  150. if ($authenticatedCustomer->image) {
  151. Storage::delete($authenticatedCustomer->image);
  152. }
  153. Event::dispatch('customer.delete.before', $authenticatedCustomer);
  154. DB::table('personal_access_tokens')
  155. ->where('tokenable_id', $authenticatedCustomer->id)
  156. ->where('tokenable_type', Customer::class)
  157. ->delete();
  158. $authenticatedCustomer->delete();
  159. Event::dispatch('customer.delete.after', $authenticatedCustomer);
  160. return null;
  161. }
  162. /**
  163. * Extract token from Authorization header or input parameter.
  164. */
  165. private function extractToken($request): ?string
  166. {
  167. $authHeader = $request->header('Authorization');
  168. if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
  169. return substr($authHeader, 7);
  170. }
  171. return $request->input('token');
  172. }
  173. /**
  174. * Get customer from Sanctum token.
  175. */
  176. private function getCustomerFromToken(string $token): ?Customer
  177. {
  178. try {
  179. if (strpos($token, '|') === false) {
  180. return null;
  181. }
  182. $personalAccessToken = \Laravel\Sanctum\PersonalAccessToken::findToken($token);
  183. if (! $personalAccessToken) {
  184. return null;
  185. }
  186. if (! $personalAccessToken->tokenable instanceof Customer) {
  187. return null;
  188. }
  189. return $personalAccessToken->tokenable;
  190. } catch (\Exception $e) {
  191. return null;
  192. }
  193. }
  194. /**
  195. * Handle image upload with base64 encoding.
  196. */
  197. private function handleImageUpload(string $imageData, Customer $customer): void
  198. {
  199. try {
  200. if (preg_match('/^data:image\/(\w+);base64,/', $imageData, $matches)) {
  201. $imageFormat = $matches[1];
  202. $base64Data = substr($imageData, strpos($imageData, ',') + 1);
  203. $decodedData = base64_decode($base64Data, true);
  204. if ($decodedData === false) {
  205. throw new InvalidInputException(__('bagistoapi::app.graphql.upload.invalid-base64'));
  206. }
  207. if (strlen($decodedData) > 5 * 1024 * 1024) {
  208. throw new InvalidInputException(__('bagistoapi::app.graphql.upload.size-exceeds-limit'));
  209. }
  210. $directory = 'customer/'.$customer->id;
  211. if ($customer->image) {
  212. Storage::delete($customer->image);
  213. }
  214. $filename = $directory.'/'.uniqid().'.'.$imageFormat;
  215. Storage::put($filename, $decodedData);
  216. $customer->image = $filename;
  217. $customer->save();
  218. Event::dispatch('customer.image.upload.after', $customer);
  219. } else {
  220. throw new InvalidInputException(__('bagistoapi::app.graphql.upload.invalid-format'));
  221. }
  222. } catch (\Exception $e) {
  223. throw new InvalidInputException(__('bagistoapi::app.graphql.upload.failed'));
  224. }
  225. }
  226. /**
  227. * Validate phone number - only digits allowed
  228. *
  229. * @throws InvalidInputException
  230. */
  231. private function validatePhone(?string $phone): void
  232. {
  233. if ($phone === null || $phone === '') {
  234. return;
  235. }
  236. // Phone should only contain digits - remove all non-digit characters
  237. $cleanedPhone = preg_replace('/[^0-9]/', '', $phone);
  238. // If the cleaned phone is different from original, it means special characters were present
  239. if ($cleanedPhone !== $phone) {
  240. throw new InvalidInputException(__('bagistoapi::app.graphql.customer.phone-special-chars-not-allowed'));
  241. }
  242. }
  243. }