GetCustomerAddressForUser.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\CustomerGraphQl\Model\Customer\Address;
  8. use Magento\Customer\Api\AddressRepositoryInterface;
  9. use Magento\Customer\Api\Data\AddressInterface;
  10. use Magento\Framework\Exception\NoSuchEntityException;
  11. use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
  12. use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
  13. /**
  14. * Get customer address for user
  15. */
  16. class GetCustomerAddressForUser
  17. {
  18. /**
  19. * @var AddressRepositoryInterface
  20. */
  21. private $addressRepository;
  22. /**
  23. * @param AddressRepositoryInterface $addressRepository
  24. */
  25. public function __construct(AddressRepositoryInterface $addressRepository)
  26. {
  27. $this->addressRepository = $addressRepository;
  28. }
  29. /**
  30. * Get customer address for user
  31. *
  32. * @param int $addressId
  33. * @param int $userId
  34. * @return AddressInterface
  35. * @throws GraphQlAuthorizationException
  36. * @throws GraphQlNoSuchEntityException
  37. */
  38. public function execute(int $addressId, int $userId): AddressInterface
  39. {
  40. try {
  41. /** @var AddressInterface $address */
  42. $address = $this->addressRepository->getById($addressId);
  43. } catch (NoSuchEntityException $e) {
  44. throw new GraphQlNoSuchEntityException(
  45. __('Address id %1 does not exist.', [$addressId])
  46. );
  47. }
  48. if ($address->getCustomerId() != $userId) {
  49. throw new GraphQlAuthorizationException(
  50. __('Current customer does not have permission to address id %1', [$addressId])
  51. );
  52. }
  53. return $address;
  54. }
  55. }