Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
RemoveItem.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
9 
10 class RemoveItem extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface
11 {
15  protected $sidebar;
16 
20  protected $logger;
21 
25  protected $jsonHelper;
26 
30  protected $resultPageFactory;
31 
35  private $formKeyValidator;
36 
44  public function __construct(
45  \Magento\Framework\App\Action\Context $context,
46  \Magento\Checkout\Model\Sidebar $sidebar,
47  \Psr\Log\LoggerInterface $logger,
48  \Magento\Framework\Json\Helper\Data $jsonHelper,
49  \Magento\Framework\View\Result\PageFactory $resultPageFactory
50  ) {
51  $this->sidebar = $sidebar;
52  $this->logger = $logger;
53  $this->jsonHelper = $jsonHelper;
54  $this->resultPageFactory = $resultPageFactory;
55  parent::__construct($context);
56  }
57 
61  public function execute()
62  {
63  if (!$this->getFormKeyValidator()->validate($this->getRequest())) {
64  return $this->resultRedirectFactory->create()->setPath('*/cart/');
65  }
66  $itemId = (int)$this->getRequest()->getParam('item_id');
67  try {
68  $this->sidebar->checkQuoteItem($itemId);
69  $this->sidebar->removeQuoteItem($itemId);
70  return $this->jsonResponse();
71  } catch (\Magento\Framework\Exception\LocalizedException $e) {
72  return $this->jsonResponse($e->getMessage());
73  } catch (\Exception $e) {
74  $this->logger->critical($e);
75  return $this->jsonResponse($e->getMessage());
76  }
77  }
78 
85  protected function jsonResponse($error = '')
86  {
87  $response = $this->sidebar->getResponseData($error);
88 
89  return $this->getResponse()->representJson(
90  $this->jsonHelper->jsonEncode($response)
91  );
92  }
93 
98  private function getFormKeyValidator()
99  {
100  if (!$this->formKeyValidator) {
101  $this->formKeyValidator = \Magento\Framework\App\ObjectManager::getInstance()
102  ->get(\Magento\Framework\Data\Form\FormKey\Validator::class);
103  }
104  return $this->formKeyValidator;
105  }
106 }
$response
Definition: 404.php:11
__construct(\Magento\Framework\App\Action\Context $context, \Magento\Checkout\Model\Sidebar $sidebar, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Json\Helper\Data $jsonHelper, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
Definition: RemoveItem.php:44