Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Price.php
Go to the documentation of this file.
1 <?php
8 
18 
19 class Price extends AddController
20 {
24  protected $storeManager;
25 
29  protected $productRepository;
30 
37  public function __construct(
38  Context $context,
42  ) {
43  $this->storeManager = $storeManager;
44  $this->productRepository = $productRepository;
45  parent::__construct($context, $customerSession);
46  }
47 
54  protected function isInternal($url)
55  {
56  if (strpos($url, 'http') === false) {
57  return false;
58  }
59  $currentStore = $this->storeManager->getStore();
60  return strpos($url, $currentStore->getBaseUrl()) === 0
61  || strpos($url, $currentStore->getBaseUrl(UrlInterface::URL_TYPE_LINK, true)) === 0;
62  }
63 
67  public function execute()
68  {
69  $backUrl = $this->getRequest()->getParam(Action::PARAM_NAME_URL_ENCODED);
70  $productId = (int)$this->getRequest()->getParam('product_id');
72  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
73  if (!$backUrl || !$productId) {
74  $resultRedirect->setPath('/');
75  return $resultRedirect;
76  }
77 
78  try {
79  /* @var $product \Magento\Catalog\Model\Product */
80  $product = $this->productRepository->getById($productId);
82  $model = $this->_objectManager->create(\Magento\ProductAlert\Model\Price::class)
83  ->setCustomerId($this->customerSession->getCustomerId())
84  ->setProductId($product->getId())
85  ->setPrice($product->getFinalPrice())
86  ->setWebsiteId(
87  $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)
88  ->getStore()
89  ->getWebsiteId()
90  );
91  $model->save();
92  $this->messageManager->addSuccess(__('You saved the alert subscription.'));
93  } catch (NoSuchEntityException $noEntityException) {
94  $this->messageManager->addError(__('There are not enough parameters.'));
95  if ($this->isInternal($backUrl)) {
96  $resultRedirect->setUrl($backUrl);
97  } else {
98  $resultRedirect->setPath('/');
99  }
100  return $resultRedirect;
101  } catch (\Exception $e) {
102  $this->messageManager->addException(
103  $e,
104  __("The alert subscription couldn't update at this time. Please try again later.")
105  );
106  }
107  $resultRedirect->setUrl($this->_redirect->getRedirectUrl());
108  return $resultRedirect;
109  }
110 }
_redirect($path, $arguments=[])
Definition: Action.php:167
__()
Definition: __.php:13
__construct(Context $context, CustomerSession $customerSession, StoreManagerInterface $storeManager, ProductRepositoryInterface $productRepository)
Definition: Price.php:37
$currentStore
Definition: queue.php:17