Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Addgroup.php
Go to the documentation of this file.
1 <?php
8 
13 
18 {
22  private $escaper;
23 
33  public function __construct(
34  \Magento\Framework\App\Action\Context $context,
35  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
36  \Magento\Checkout\Model\Session $checkoutSession,
38  \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
40  Escaper $escaper = null
41  ) {
42  $this->escaper = $escaper ?: ObjectManager::getInstance()->get(\Magento\Framework\Escaper::class);
43  parent::__construct($context, $scopeConfig, $checkoutSession, $storeManager, $formKeyValidator, $cart);
44  }
45 
49  public function execute()
50  {
51  $orderItemIds = $this->getRequest()->getPost('order_items');
52  if (is_array($orderItemIds)) {
53  $itemsCollection = $this->_objectManager->create(\Magento\Sales\Model\Order\Item::class)
54  ->getCollection()
55  ->addIdFilter($orderItemIds)
56  ->load();
57  /* @var $itemsCollection \Magento\Sales\Model\ResourceModel\Order\Item\Collection */
58  foreach ($itemsCollection as $item) {
59  try {
60  $this->addOrderItem($item);
61  } catch (\Magento\Framework\Exception\LocalizedException $e) {
62  if ($this->_checkoutSession->getUseNotice(true)) {
63  $this->messageManager->addNoticeMessage($e->getMessage());
64  } else {
65  $this->messageManager->addErrorMessage($e->getMessage());
66  }
67  } catch (\Exception $e) {
68  $this->messageManager->addExceptionMessage(
69  $e,
70  __('We can\'t add this item to your shopping cart right now.')
71  );
72  $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
73  return $this->_goBack();
74  }
75  }
76  $this->cart->save();
77  }
78  return $this->_goBack();
79  }
80 
89  private function addOrderItem(Item $item)
90  {
92  $session = $this->cart->getCustomerSession();
93  if ($session->isLoggedIn()) {
94  $orderCustomerId = $item->getOrder()->getCustomerId();
95  $currentCustomerId = $session->getCustomer()->getId();
96  if ($orderCustomerId == $currentCustomerId) {
97  $this->cart->addOrderItem($item, 1);
98  if (!$this->cart->getQuote()->getHasError()) {
99  $message = __(
100  'You added %1 to your shopping cart.',
101  $this->escaper->escapeHtml($item->getName())
102  );
103  $this->messageManager->addSuccessMessage($message);
104  }
105  }
106  }
107  }
108 }
__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, Escaper $escaper=null)
Definition: Addgroup.php:33
$storeManager
__()
Definition: __.php:13
$message
_goBack($backUrl=null)
Definition: Cart.php:73