1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
<?php
/**
*
* SM CartQuickPro - Version 1.1.0
* Copyright (c) 2017 YouTech Company. All Rights Reserved.
* @license - Copyrighted Commercial Software
* Author: YouTech Company
* Websites: http://www.magentech.com
*/
namespace Sm\CartQuickPro\Controller\Cart;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Cart as CustomerCart;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Add extends \Magento\Checkout\Controller\Cart
{
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
* @param CustomerCart $cart
* @param ProductRepositoryInterface $productRepository
* @codeCoverageIgnore
*/
public function __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
) {
parent::__construct(
$context,
$scopeConfig,
$checkoutSession,
$storeManager,
$formKeyValidator,
$cart
);
$this->productRepository = $productRepository;
}
/**
* Initialize product instance from request data
*
* @return \Magento\Catalog\Model\Product|false
*/
protected function _initProduct()
{
$productId = (int)$this->getRequest()->getParam('product');
if ($productId) {
$storeId = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
try {
return $this->productRepository->getById($productId, false, $storeId);
} catch (NoSuchEntityException $e) {
return false;
}
}
return false;
}
/**
* Add product to shopping cart action
*
* @return \Magento\Framework\Controller\Result\Redirect
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
$result = [];
if (!$this->_formKeyValidator->validate($this->getRequest())) {
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new \Zend_Filter_LocalizedToNormalized(
['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()]
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
return $this->goBack();
}
$this->cart->addProduct($product, $params);
if (!empty($related)) {
$this->cart->addProductsByIds(explode(',', $related));
}
$this->cart->save();
/**
* @todo remove wishlist observer \Magento\Wishlist\Observer\AddToCart
*/
$this->_eventManager->dispatch(
'checkout_cart_add_product_complete',
['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
);
if (!$this->_checkoutSession->getNoCartRedirect(true)) {
if (!$this->cart->getQuote()->getHasError()) {
$message = __(
'You added %1 to your shopping cart.',
$product->getName()
);
$this->messageManager->addSuccessMessage($message);
$result['success'] = true;
$result['messages'] = $message;
if (isset($params['isCheckoutPage'])){
$_layout = $this->_objectManager->get('Magento\Framework\View\LayoutInterface');
$_layout->getUpdate()->load([ 'cartquickpro_checkout_cart_index', 'checkout_cart_item_renderers','checkout_item_price_renderers']);
$_layout->generateXml();
$_output = $_layout->getOutput();
$result['content'] = $_output;
$result['isPageCheckoutContent'] = true;
}
}
}
} catch (\Magento\Framework\Exception\LocalizedException $e) {
if ($this->_checkoutSession->getUseNotice(true)) {
$this->messageManager->addNotice(
$this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage())
);
$result['messages'] = $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage());
$result['success'] = true;
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->messageManager->addError(
$this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
);
}
$result['messages'] = join(', ', $messages);
$result['success'] = false;
}
$storeManager = $this->_objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$baseUrl= $storeManager->getStore()->getBaseUrl();
$url = $baseUrl.'cartquickpro/catalog_product/options/id/'.$params['product'];
if (!$url) {
$cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl();
$url = $this->_redirect->getRedirectUrl($cartUrl);
}
$result['url'] = $url;
} catch (\Exception $e) {
$this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now.'));
$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
$result['messages'] = __('We can\'t add this item to your shopping cart right now.');
$result['success'] = false;
}
$result['isAddToCartBtn'] = (!isset($params['isCheckoutPage']) && $this->cart->getItemsCount()) ? true : false ;
return $this->_jsonResponse($result);
}
protected function _jsonResponse($result)
{
return $this->getResponse()->representJson(
$this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
);
}
/**
* Resolve response
*
* @param string $backUrl
* @param \Magento\Catalog\Model\Product $product
* @return $this|\Magento\Framework\Controller\Result\Redirect
*/
protected function goBack($backUrl = null, $product = null)
{
if (!$this->getRequest()->isAjax()) {
return parent::_goBack($backUrl);
}
$result = [];
if ($backUrl || $backUrl = $this->getBackUrl()) {
$result['backUrl'] = $backUrl;
} else {
if ($product && !$product->getIsSalable()) {
$result['product'] = [
'statusText' => __('Out of stock')
];
}
}
$this->getResponse()->representJson(
$this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
);
}
}