|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Omikron\FactFinder\Oxid\Controller; |
| 6 | + |
| 7 | +use OxidEsales\Eshop\Application\Controller\FrontendController; |
| 8 | +use OxidEsales\Eshop\Application\Model\Article; |
| 9 | +use OxidEsales\Eshop\Core\Registry; |
| 10 | + |
| 11 | +class AddToCartController extends FrontendController |
| 12 | +{ |
| 13 | + public function addToCart(): void |
| 14 | + { |
| 15 | + $productNumber = Registry::getRequest()->getRequestParameter('productNumber'); |
| 16 | + $amount = 1; |
| 17 | + $utilsView = Registry::getUtilsView(); |
| 18 | + |
| 19 | + try { |
| 20 | + if (!$productNumber) { |
| 21 | + throw new \Exception("Product with number $productNumber does not exist"); |
| 22 | + } |
| 23 | + |
| 24 | + $product = oxNew(Article::class); |
| 25 | + $productId = $this->getProductIdByNumber($productNumber); |
| 26 | + |
| 27 | + if (!$productId || !$product->load($productId) || !$product->isBuyable()) { |
| 28 | + throw new \Exception("Product with number $productNumber does not exist or is not buyable"); |
| 29 | + } |
| 30 | + |
| 31 | + $basket = Registry::getSession()->getBasket(); |
| 32 | + $basket->addToBasket($productId, $amount); |
| 33 | + $basket->calculateBasket(true); |
| 34 | + $utilsView->addErrorToDisplay('Product was added to the cart successfully.'); |
| 35 | + $this->redirectToReferer(); |
| 36 | + } catch (\Exception $e) { |
| 37 | + $utilsView->addErrorToDisplay('Error: ' . $e->getMessage(), false, false, 'error_message'); |
| 38 | + $this->redirectToReferer(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private function getProductIdByNumber($productNumber) |
| 43 | + { |
| 44 | + $database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); |
| 45 | + $sQuery = 'SELECT oxid FROM oxarticles WHERE oxartnum = ? AND oxactive = 1'; |
| 46 | + |
| 47 | + return $database->getOne($sQuery, [$productNumber]); |
| 48 | + } |
| 49 | + |
| 50 | + private function redirectToReferer(): void |
| 51 | + { |
| 52 | + $referer = $_SERVER['HTTP_REFERER'] ?? Registry::getConfig()->getCurrentShopUrl(); |
| 53 | + Registry::getUtils()->redirect($referer, false, 302); |
| 54 | + } |
| 55 | +} |
0 commit comments