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 
15 
17 {
21  protected $productRepository;
22 
28  public function __construct(
29  Context $context,
32  ) {
33  $this->productRepository = $productRepository;
34  parent::__construct($context, $customerSession);
35  }
36 
40  public function execute()
41  {
42  $productId = (int)$this->getRequest()->getParam('product');
44  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
45  if (!$productId) {
46  $resultRedirect->setPath('/');
47  return $resultRedirect;
48  }
49 
50  try {
51  $product = $this->productRepository->getById($productId);
52  if (!$product->isVisibleInCatalog()) {
53  throw new NoSuchEntityException();
54  }
55 
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  ->loadByParam();
65  if ($model->getId()) {
66  $model->delete();
67  }
68  $this->messageManager->addSuccess(__('You will no longer receive stock alerts for this product.'));
69  } catch (NoSuchEntityException $noEntityException) {
70  $this->messageManager->addError(__('The product was not found.'));
71  $resultRedirect->setPath('customer/account/');
72  return $resultRedirect;
73  } catch (\Exception $e) {
74  $this->messageManager->addException(
75  $e,
76  __("The alert subscription couldn't update at this time. Please try again later.")
77  );
78  }
79  $resultRedirect->setUrl($product->getProductUrl());
80  return $resultRedirect;
81  }
82 }
__construct(Context $context, CustomerSession $customerSession, ProductRepositoryInterface $productRepository)
Definition: Stock.php:28
__()
Definition: __.php:13