<?php
namespace ZweiPunktSeoKampfpreise\Subscriber;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use ZweiPunktSeoKampfpreise\Service\ConfigService;
use ZweiPunktSeoKampfpreise\Service\ProductPriceUpdater;
use ZweiPunktSeoKampfpreise\Service\RequestChecker;
/**
* This subscriber updated the product price if the fightprice parameter is
* set correctly and adds the product ID to the session so the product price
* will be updated in feature requests even if the fightprice parameter isn't
* set at the second visit.
*/
class DetailSubscriber implements EventSubscriberInterface
{
private SessionInterface $session;
private SalesChannelProductEntity $product;
private ConfigService $configService;
private RequestChecker $requestChecker;
private ProductPriceUpdater $productPriceUpdater;
public function __construct(
ConfigService $configService,
RequestChecker $requestChecker,
ProductPriceUpdater $productPriceUpdater
) {
$this->configService = $configService;
$this->requestChecker = $requestChecker;
$this->productPriceUpdater = $productPriceUpdater;
}
/**
* @return array<string, string>
*/
public static function getSubscribedEvents()
{
return [
ProductPageLoadedEvent::class => 'productPageLoaded',
];
}
/**
* @param ProductPageLoadedEvent $event
*/
public function productPageLoaded(
ProductPageLoadedEvent $event
): void {
$this->configService->setSalesChannelId(
$event->getSalesChannelContext()->getSalesChannelId()
);
$this->requestChecker->setRequest($event->getRequest());
$this->session = $event->getRequest()->getSession();
if (!$this->requestChecker->updatePrice()) {
return;
}
$this->product = $event->getPage()->getProduct();
$ruleId = $this->configService->get('fightPriceRule');
$prices = $this->product->getPrices();
$fightPrice = null;
foreach ($prices as $productPriceEntity) {
if ($ruleId == $productPriceEntity->getRuleId()) {
$fightPrice = $productPriceEntity;
}
}
if (is_null($fightPrice)) {
return;
}
if (!$this->requestChecker->isSeoPage()) {
return;
}
$this
->productPriceUpdater
->updatePrice($ruleId, $this->product)
;
$this->addFightPriceToSession(
$fightPrice->getPrice()->first()->getGross()
);
}
private function addFightPriceToSession(float $price): void
{
$history = $this->session->get('priceHistory', []);
$history[$this->product->getId()] = round($price, 2);
$this->session->set('priceHistory', $history);
}
}