Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Cart.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Catalog\Model\Product\Exception as ProductException;
9 use Magento\Checkout\Helper\Cart as CartHelper;
11 use Magento\Framework\App\Action\Context as ActionContext;
16 use Magento\Wishlist\Model\Item\OptionFactory;
17 use Magento\Wishlist\Model\ItemFactory;
19 
24 {
28  protected $cart;
29 
33  protected $optionFactory;
34 
38  protected $itemFactory;
39 
43  protected $cartHelper;
44 
48  protected $escaper;
49 
58  public function __construct(
59  ActionContext $context,
61  OptionFactory $optionFactory,
62  ItemFactory $itemFactory,
63  CartHelper $cartHelper,
65  ) {
66  $this->cart = $cart;
67  $this->optionFactory = $optionFactory;
68  $this->itemFactory = $itemFactory;
69  $this->cartHelper = $cartHelper;
70  $this->escaper = $escaper;
71  parent::__construct($context);
72  }
73 
82  public function execute()
83  {
84  $itemId = (int)$this->getRequest()->getParam('item');
85 
86  /* @var $item Item */
87  $item = $this->itemFactory->create()
88  ->load($itemId);
89 
90  $redirectUrl = $this->_redirect->getRefererUrl();
91 
92  try {
94  $options = $this->optionFactory->create()
95  ->getCollection()->addItemFilter([$itemId]);
96  $item->setOptions($options->getOptionsByItem($itemId));
97  $item->addToCart($this->cart);
98 
99  $this->cart->save();
100 
101  if (!$this->cart->getQuote()->getHasError()) {
102  $message = __(
103  'You added %1 to your shopping cart.',
104  $this->escaper->escapeHtml($item->getProduct()->getName())
105  );
106  $this->messageManager->addSuccess($message);
107  }
108 
109  if ($this->cartHelper->getShouldRedirectToCart()) {
110  $redirectUrl = $this->cartHelper->getCartUrl();
111  }
112  } catch (ProductException $e) {
113  $this->messageManager->addError(__('This product(s) is out of stock.'));
114  } catch (LocalizedException $e) {
115  $this->messageManager->addNotice($e->getMessage());
116  $redirectUrl = $item->getProductUrl();
117  } catch (\Exception $e) {
118  $this->messageManager->addException($e, __('We can\'t add the item to the cart right now.'));
119  }
121  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
122  $resultRedirect->setUrl($redirectUrl);
123  return $resultRedirect;
124  }
125 }
_redirect($path, $arguments=[])
Definition: Action.php:167
__()
Definition: __.php:13
$message
__construct(ActionContext $context, CustomerCart $cart, OptionFactory $optionFactory, ItemFactory $itemFactory, CartHelper $cartHelper, Escaper $escaper)
Definition: Cart.php:58