Delete.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Customer\Controller\Adminhtml\Address;
  9. use Magento\Backend\App\Action;
  10. use Magento\Framework\App\Action\HttpPostActionInterface;
  11. use Magento\Framework\Controller\Result\Json;
  12. use Magento\Framework\Controller\Result\JsonFactory;
  13. use Magento\Customer\Api\AddressRepositoryInterface;
  14. use Psr\Log\LoggerInterface;
  15. /**
  16. * Button for deletion of customer address in admin
  17. */
  18. class Delete extends Action implements HttpPostActionInterface
  19. {
  20. /**
  21. * Authorization level of a basic admin session
  22. *
  23. * @see _isAllowed()
  24. */
  25. public const ADMIN_RESOURCE = 'Magento_Customer::manage';
  26. /**
  27. * @var AddressRepositoryInterface
  28. */
  29. private $addressRepository;
  30. /**
  31. * @var JsonFactory
  32. */
  33. private $resultJsonFactory;
  34. /**
  35. * @var LoggerInterface
  36. */
  37. private $logger;
  38. /**
  39. * @param Action\Context $context
  40. * @param AddressRepositoryInterface $addressRepository
  41. * @param JsonFactory $resultJsonFactory
  42. * @param LoggerInterface $logger
  43. */
  44. public function __construct(
  45. Action\Context $context,
  46. AddressRepositoryInterface $addressRepository,
  47. JsonFactory $resultJsonFactory,
  48. LoggerInterface $logger
  49. ) {
  50. parent::__construct($context);
  51. $this->addressRepository = $addressRepository;
  52. $this->resultJsonFactory = $resultJsonFactory;
  53. $this->logger = $logger;
  54. }
  55. /**
  56. * Delete customer address action
  57. *
  58. * @return Json
  59. * @throws \Magento\Framework\Exception\LocalizedException
  60. */
  61. public function execute(): Json
  62. {
  63. $customerId = $this->getRequest()->getParam('parent_id', false);
  64. $addressId = $this->getRequest()->getParam('id', false);
  65. $error = false;
  66. $message = '';
  67. if ($addressId && $this->addressRepository->getById($addressId)->getCustomerId() === $customerId) {
  68. try {
  69. $this->addressRepository->deleteById($addressId);
  70. $message = __('You deleted the address.');
  71. } catch (\Exception $e) {
  72. $error = true;
  73. $message = __('We can\'t delete the address right now.');
  74. $this->logger->critical($e);
  75. }
  76. }
  77. $resultJson = $this->resultJsonFactory->create();
  78. $resultJson->setData(
  79. [
  80. 'message' => $message,
  81. 'error' => $error,
  82. ]
  83. );
  84. return $resultJson;
  85. }
  86. }