/
Add.php
197 lines (177 loc) · 6.79 KB
/
Add.php
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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Checkout\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::class
)->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
* @throws \Magento\Framework\Exception\NotFoundException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
if (!$this->getRequest()->isPost()) {
throw new \Magento\Framework\Exception\NotFoundException(__('Page not found.'));
}
if (!$this->_formKeyValidator->validate($this->getRequest())) {
$this->messageManager->addErrorMessage(
__('Your session has expired')
);
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::class
)->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);
}
return $this->goBack(null, $product);
}
} catch (\Magento\Framework\Exception\LocalizedException $e) {
if ($this->_checkoutSession->getUseNotice(true)) {
$this->messageManager->addNotice(
$this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
);
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->messageManager->addError(
$this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($message)
);
}
}
$url = $this->_checkoutSession->getRedirectUrl(true);
if (!$url) {
$cartUrl = $this->_objectManager->get(\Magento\Checkout\Helper\Cart::class)->getCartUrl();
$url = $this->_redirect->getRedirectUrl($cartUrl);
}
return $this->goBack($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::class)->critical($e);
return $this->goBack();
}
}
/**
* 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::class)->jsonEncode($result)
);
}
}