Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
DeleteAction.php
Go to the documentation of this file.
1 <?php
7 
20 
25 {
26  const WRONG_REQUEST = 1;
27 
28  const WRONG_TOKEN = 2;
29 
30  const ACTION_EXCEPTION = 3;
31 
35  private $errorsMap = [];
36 
40  private $jsonFactory;
41 
45  private $fkValidator;
46 
50  private $tokenRepository;
51 
55  private $paymentTokenManagement;
56 
65  public function __construct(
66  Context $context,
68  JsonFactory $jsonFactory,
69  Validator $fkValidator,
70  PaymentTokenRepositoryInterface $tokenRepository,
71  PaymentTokenManagement $paymentTokenManagement
72  ) {
73  parent::__construct($context, $customerSession);
74  $this->jsonFactory = $jsonFactory;
75  $this->fkValidator = $fkValidator;
76  $this->tokenRepository = $tokenRepository;
77  $this->paymentTokenManagement = $paymentTokenManagement;
78 
79  $this->errorsMap = [
80  self::WRONG_TOKEN => __('No token found.'),
81  self::WRONG_REQUEST => __('Wrong request.'),
82  self::ACTION_EXCEPTION => __('Deletion failure. Please try again.')
83  ];
84  }
85 
92  public function execute()
93  {
95  if (!$request instanceof Http) {
96  return $this->createErrorResponse(self::WRONG_REQUEST);
97  }
98 
99  if (!$this->fkValidator->validate($request)) {
100  return $this->createErrorResponse(self::WRONG_REQUEST);
101  }
102 
103  $paymentToken = $this->getPaymentToken($request);
104  if ($paymentToken === null) {
105  return $this->createErrorResponse(self::WRONG_TOKEN);
106  }
107 
108  try {
109  $this->tokenRepository->delete($paymentToken);
110  } catch (\Exception $e) {
111  return $this->createErrorResponse(self::ACTION_EXCEPTION);
112  }
113 
114  return $this->createSuccessMessage();
115  }
116 
121  private function createErrorResponse($errorCode)
122  {
123  $this->messageManager->addErrorMessage(
124  $this->errorsMap[$errorCode]
125  );
126 
127  return $this->_redirect('vault/cards/listaction');
128  }
129 
133  private function createSuccessMessage()
134  {
135  $this->messageManager->addSuccessMessage(
136  __('Stored Payment Method was successfully removed')
137  );
138  return $this->_redirect('vault/cards/listaction');
139  }
140 
145  private function getPaymentToken(Http $request)
146  {
147  $publicHash = $request->getPostValue(PaymentTokenInterface::PUBLIC_HASH);
148 
149  if ($publicHash === null) {
150  return null;
151  }
152 
153  return $this->paymentTokenManagement->getByPublicHash(
154  $publicHash,
155  $this->customerSession->getCustomerId()
156  );
157  }
158 }
_redirect($path, $arguments=[])
Definition: Action.php:167
__()
Definition: __.php:13
$tokenRepository
__construct(Context $context, Session $customerSession, JsonFactory $jsonFactory, Validator $fkValidator, PaymentTokenRepositoryInterface $tokenRepository, PaymentTokenManagement $paymentTokenManagement)