Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
All Data Structures Namespaces Files Functions Variables Pages
Add.php
Go to the documentation of this file.
1 <?php
8 
9 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
13 
20 {
24  protected $productRepository;
25 
36  public function __construct(
37  \Magento\Framework\App\Action\Context $context,
38  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
39  \Magento\Checkout\Model\Session $checkoutSession,
41  \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
44  ) {
45  parent::__construct(
46  $context,
47  $scopeConfig,
48  $checkoutSession,
50  $formKeyValidator,
51  $cart
52  );
53  $this->productRepository = $productRepository;
54  }
55 
61  protected function _initProduct()
62  {
63  $productId = (int)$this->getRequest()->getParam('product');
64  if ($productId) {
65  $storeId = $this->_objectManager->get(
66  \Magento\Store\Model\StoreManagerInterface::class
67  )->getStore()->getId();
68  try {
69  return $this->productRepository->getById($productId, false, $storeId);
70  } catch (NoSuchEntityException $e) {
71  return false;
72  }
73  }
74  return false;
75  }
76 
83  public function execute()
84  {
85  if (!$this->_formKeyValidator->validate($this->getRequest())) {
86  $this->messageManager->addErrorMessage(
87  __('Your session has expired')
88  );
89  return $this->resultRedirectFactory->create()->setPath('*/*/');
90  }
91 
92  $params = $this->getRequest()->getParams();
93 
94  try {
95  if (isset($params['qty'])) {
96  $filter = new \Zend_Filter_LocalizedToNormalized(
97  ['locale' => $this->_objectManager->get(
98  \Magento\Framework\Locale\ResolverInterface::class
99  )->getLocale()]
100  );
101  $params['qty'] = $filter->filter($params['qty']);
102  }
103 
104  $product = $this->_initProduct();
105  $related = $this->getRequest()->getParam('related_product');
106 
110  if (!$product) {
111  return $this->goBack();
112  }
113 
114  $this->cart->addProduct($product, $params);
115  if (!empty($related)) {
116  $this->cart->addProductsByIds(explode(',', $related));
117  }
118 
119  $this->cart->save();
120 
124  $this->_eventManager->dispatch(
125  'checkout_cart_add_product_complete',
126  ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
127  );
128 
129  if (!$this->_checkoutSession->getNoCartRedirect(true)) {
130  if (!$this->cart->getQuote()->getHasError()) {
131  if ($this->shouldRedirectToCart()) {
132  $message = __(
133  'You added %1 to your shopping cart.',
134  $product->getName()
135  );
136  $this->messageManager->addSuccessMessage($message);
137  } else {
138  $this->messageManager->addComplexSuccessMessage(
139  'addCartSuccessMessage',
140  [
141  'product_name' => $product->getName(),
142  'cart_url' => $this->getCartUrl(),
143  ]
144  );
145  }
146  }
147  return $this->goBack(null, $product);
148  }
149  } catch (\Magento\Framework\Exception\LocalizedException $e) {
150  if ($this->_checkoutSession->getUseNotice(true)) {
151  $this->messageManager->addNoticeMessage(
152  $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
153  );
154  } else {
155  $messages = array_unique(explode("\n", $e->getMessage()));
156  foreach ($messages as $message) {
157  $this->messageManager->addErrorMessage(
158  $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($message)
159  );
160  }
161  }
162 
163  $url = $this->_checkoutSession->getRedirectUrl(true);
164 
165  if (!$url) {
166  $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
167  }
168 
169  return $this->goBack($url);
170  } catch (\Exception $e) {
171  $this->messageManager->addExceptionMessage(
172  $e,
173  __('We can\'t add this item to your shopping cart right now.')
174  );
175  $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
176  return $this->goBack();
177  }
178  }
179 
187  protected function goBack($backUrl = null, $product = null)
188  {
189  if (!$this->getRequest()->isAjax()) {
190  return parent::_goBack($backUrl);
191  }
192 
193  $result = [];
194 
195  if ($backUrl || $backUrl = $this->getBackUrl()) {
196  $result['backUrl'] = $backUrl;
197  } else {
198  if ($product && !$product->getIsSalable()) {
199  $result['product'] = [
200  'statusText' => __('Out of stock')
201  ];
202  }
203  }
204 
205  $this->getResponse()->representJson(
206  $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result)
207  );
208  }
209 
215  private function getCartUrl()
216  {
217  return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
218  }
219 
225  private function shouldRedirectToCart()
226  {
227  return $this->_scopeConfig->isSetFlag(
228  'checkout/cart/redirect_to_cart',
230  );
231  }
232 }
goBack($backUrl=null, $product=null)
Definition: Add.php:187
getBackUrl($defaultUrl=null)
Definition: Cart.php:112
_redirect($path, $arguments=[])
Definition: Action.php:167
$storeManager
__()
Definition: __.php:13
$message
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
__construct(\Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Checkout\Model\Session $checkoutSession, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator, CustomerCart $cart, ProductRepositoryInterface $productRepository)
Definition: Add.php:36