<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Customer\Event\CustomerRegisterEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WbfkExtensions\Service\GeneralTermsFactory;
class CheckoutPageSubscriber implements EventSubscriberInterface
{
public function __construct(
protected readonly GeneralTermsFactory $generalTermsFactory,
protected readonly LoggerInterface $logger
)
{
}
public static function getSubscribedEvents(): array
{
return [
CustomerRegisterEvent::class => 'onCustomerRegisterEvent',
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced',
];
}
public function onCustomerRegisterEvent(CustomerRegisterEvent $event): void
{
$ipAddress = $this->getIpAddress();
$this->generalTermsFactory->trackGeneralTerms($event->getCustomerId(), $ipAddress);
}
public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
try {
$ipAddress = $this->getIpAddress();
$this->generalTermsFactory->trackGeneralTerms($event->getCustomerId(), $ipAddress, $event->getOrderId());
} catch (\Exception $exception) {
//Don't let the App die because of tracking issues
$this->logger->error($exception->getMessage());
}
}
protected function getIpAddress(): ?string
{
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
// the format of the header is "X-Forwarded-For: <client>, <proxy1>, <proxy2>"
// we only care for the client IP
$ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim($ipAddresses[0]);
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
}