<?php
declare(strict_types=1);
namespace Tanmar\GoogleAdsTracking\Storefront\Page\Product;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Tanmar\GoogleAdsTracking\Storefront\BaseSubscriber;
use Tanmar\GoogleAdsTracking\Components\Helper\LoggerHelper;
use Tanmar\GoogleAdsTracking\Service\ConfigService;
use Tanmar\GoogleAdsTracking\Service\Article\ArticleIdentifierService;
use Tanmar\GoogleAdsTracking\Service\RemarketingEvent\RemarketingEventService;
class ProductPageSubscriber extends BaseSubscriber implements EventSubscriberInterface {
protected RemarketingEventService $remarketingEventService;
public function __construct(ConfigService $configService, LoggerHelper $loggerHelper, ArticleIdentifierService $articleIdentifierService, RemarketingEventService $remarketingEventService) {
parent::__construct($configService, $loggerHelper, $articleIdentifierService);
$this->remarketingEventService = $remarketingEventService;
}
public static function getSubscribedEvents(): array {
return [
ProductPageLoadedEvent::class => 'onProductPageLoaded'
];
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void {
try {
$googleAdsData = $this->getExtension($event);
if (!is_null($googleAdsData) && $this->getConfig()->isRetargetingActive()) {
$eventData = $this->remarketingEventService->getEventData(array($event->getPage()->getProduct()), $this->getPrice($event->getPage()->getProduct()));
$googleAdsData->assign([
'eventName' => RemarketingEventService::GOOGLE_ADS_EVENT_NAME_PRODUCT,
'eventData' => (count($eventData) > 0) ? $eventData : false
]);
}
$this->addExtension($event, $googleAdsData);
} catch (\Throwable $e) {
$this->loggerHelper->logThrowable($e);
}
}
protected function getPrice(SalesChannelProductEntity $product): float {
$price = 0;
try {
$calculatedPrices = $product->getCalculatedPrices();
$calculatedPrice = $product->getCalculatedPrice();
if (!is_null($calculatedPrices) && !is_null($calculatedPrices->getElements()) && count($calculatedPrices->getElements()) > 0) {
$price = $calculatedPrices->getElements()[0]->getUnitPrice();
} elseif (!is_null($calculatedPrice) && !is_null($calculatedPrice->getTotalPrice())) {
$price = $calculatedPrice->getTotalPrice();
}
} catch (\Throwable $e) {
$this->loggerHelper->logThrowable($e);
}
return $price;
}
}