Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Stock.php
Go to the documentation of this file.
1 <?php
8 
16 
17 class Stock extends AddController
18 {
22  protected $productRepository;
23 
29  public function __construct(
30  Context $context,
33  ) {
34  $this->productRepository = $productRepository;
35  parent::__construct($context, $customerSession);
36  }
37 
41  public function execute()
42  {
43  $backUrl = $this->getRequest()->getParam(Action::PARAM_NAME_URL_ENCODED);
44  $productId = (int)$this->getRequest()->getParam('product_id');
46  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
47  if (!$backUrl || !$productId) {
48  $resultRedirect->setPath('/');
49  return $resultRedirect;
50  }
51 
52  try {
53  /* @var $product \Magento\Catalog\Model\Product */
54  $product = $this->productRepository->getById($productId);
56  $model = $this->_objectManager->create(\Magento\ProductAlert\Model\Stock::class)
57  ->setCustomerId($this->customerSession->getCustomerId())
58  ->setProductId($product->getId())
59  ->setWebsiteId(
60  $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)
61  ->getStore()
62  ->getWebsiteId()
63  );
64  $model->save();
65  $this->messageManager->addSuccess(__('Alert subscription has been saved.'));
66  } catch (NoSuchEntityException $noEntityException) {
67  $this->messageManager->addError(__('There are not enough parameters.'));
68  $resultRedirect->setUrl($backUrl);
69  return $resultRedirect;
70  } catch (\Exception $e) {
71  $this->messageManager->addException(
72  $e,
73  __("The alert subscription couldn't update at this time. Please try again later.")
74  );
75  }
76  $resultRedirect->setUrl($this->_redirect->getRedirectUrl());
77  return $resultRedirect;
78  }
79 }
_redirect($path, $arguments=[])
Definition: Action.php:167
__()
Definition: __.php:13
__construct(Context $context, CustomerSession $customerSession, ProductRepositoryInterface $productRepository)
Definition: Stock.php:29