<?php
declare(strict_types=1);
namespace FourtwosixThemeCustomization\Subscriber;
use FourtwosixThemeCustomization\FourtwosixThemeCustomization as Plugin;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Page\PageLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Shopware\Core\Defaults;
use Shopware\Core\Content\Product\Aggregate\ProductPrice\ProductPriceCollection;
class ProductDetailSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoadedEvent'
];
}
public function onProductPageLoadedEvent(PageLoadedEvent $event)
{
if ($event->getSalesChannelContext()->getCustomer()) {
return; // Logged in = Customer
}
$hasCheaperLoggedInPrice = $this->hasCheaperLoggedInPrice($event->getPage()->getProduct());
if($hasCheaperLoggedInPrice) {
$extensions = $event->getPage()->getExtensions();
$extensions['fourtwosix']['specialDiscount'] = true;
$event->getPage()->setExtensions($extensions);
}
}
private function hasCheaperLoggedInPrice($product) : bool {
if(empty($product) || empty($product->getPrice()) || empty($product->getPrices())) return false;
$grossPrice = $product->getPrice()->get(Defaults::CURRENCY)->getGross();
$grossPriceLoggedIn = $this->getGrossPriceByRuleId($product->getPrices(), Plugin::CUSTOMER_RULE_ID);
return $grossPriceLoggedIn !== false && $grossPriceLoggedIn < $grossPrice;
}
private function getGrossPriceByRuleId(ProductPriceCollection $priceRules, string $ruleIdToFind): float|false
{
foreach ($priceRules as $rule) {
if (\strtolower($rule->getRuleId()) === \strtolower($ruleIdToFind)) {
return empty($rule->getPrice()) ? \false : $rule->getPrice()->get(Defaults::CURRENCY)->getGross();
}
}
return \false;
}
}