custom/plugins/FourtwosixThemeCustomization/src/Subscriber/ProductDetailSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace FourtwosixThemeCustomization\Subscriber;
  4. use FourtwosixThemeCustomization\FourtwosixThemeCustomization as Plugin;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Shopware\Storefront\Page\PageLoadedEvent;
  7. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  8. use Shopware\Core\Defaults;
  9. use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceCollection;
  10. class ProductDetailSubscriber implements EventSubscriberInterface
  11. {
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         return [
  15.             ProductPageLoadedEvent::class => 'onProductPageLoadedEvent'
  16.         ];
  17.     }
  18.     public function onProductPageLoadedEvent(PageLoadedEvent $event)
  19.     {
  20.         if ($event->getSalesChannelContext()->getCustomer()) {
  21.             return; // Logged in = Customer
  22.         }
  23.         $hasCheaperLoggedInPrice $this->hasCheaperLoggedInPrice($event->getPage()->getProduct());
  24.         if($hasCheaperLoggedInPrice) {
  25.             $extensions $event->getPage()->getExtensions();
  26.             $extensions['fourtwosix']['specialDiscount'] = true;
  27.             $event->getPage()->setExtensions($extensions);
  28.         }
  29.     }
  30.     private function hasCheaperLoggedInPrice($product) : bool {
  31.         if(empty($product) || empty($product->getPrice()) || empty($product->getPrices())) return false;
  32.         $grossPrice $product->getPrice()->get(Defaults::CURRENCY)->getGross();
  33.         $grossPriceLoggedIn $this->getGrossPriceByRuleId($product->getPrices(), Plugin::CUSTOMER_RULE_ID);
  34.         return $grossPriceLoggedIn !== false && $grossPriceLoggedIn $grossPrice;
  35.     }
  36.     private function getGrossPriceByRuleId(ProductPriceCollection $priceRulesstring $ruleIdToFind): float|false
  37.     {
  38.         foreach ($priceRules as $rule) {
  39.             if (\strtolower($rule->getRuleId()) === \strtolower($ruleIdToFind)) {
  40.                 return empty($rule->getPrice()) ? \false $rule->getPrice()->get(Defaults::CURRENCY)->getGross();
  41.             }
  42.         }
  43.         return \false;
  44.     }
  45. }