|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Setono\SyliusGoogleAdsPlugin\EventSubscriber\ConversionProcessing; |
| 6 | + |
| 7 | +use Setono\SyliusGoogleAdsPlugin\Event\PreSetClickConversionDataEvent; |
| 8 | +use Setono\SyliusGoogleAdsPlugin\Repository\MerchantMappingRepositoryInterface; |
| 9 | +use Sylius\Component\Core\Model\OrderInterface; |
| 10 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 11 | + |
| 12 | +final class AddCartDataSubscriber implements EventSubscriberInterface |
| 13 | +{ |
| 14 | + public function __construct(private readonly MerchantMappingRepositoryInterface $merchantMappingRepository) |
| 15 | + { |
| 16 | + } |
| 17 | + |
| 18 | + public static function getSubscribedEvents(): array |
| 19 | + { |
| 20 | + return [ |
| 21 | + PreSetClickConversionDataEvent::class => 'add', |
| 22 | + ]; |
| 23 | + } |
| 24 | + |
| 25 | + public function add(PreSetClickConversionDataEvent $event): void |
| 26 | + { |
| 27 | + $order = $event->conversion->getOrder(); |
| 28 | + if (null === $order) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + $channel = $order->getChannel(); |
| 33 | + if (null === $channel) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + $localeCode = $order->getLocaleCode(); |
| 38 | + if (null === $localeCode) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + $merchantId = $this->merchantMappingRepository->findOneByChannel($channel)?->getMerchantId(); |
| 43 | + if (null === $merchantId) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + $countryCode = $order->getBillingAddress()?->getCountryCode(); |
| 48 | + if (null === $countryCode) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + $items = self::getItems($order); |
| 53 | + if ([] === $items) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + $event->data['cart_data'] = [ |
| 58 | + 'merchant_id' => $merchantId, |
| 59 | + 'feed_country_code' => $countryCode, |
| 60 | + 'feed_language_code' => $localeCode, |
| 61 | + 'local_transaction_cost' => 0, // TODO: Sum of all transaction level discounts, such as free shipping and coupon discounts for the whole cart. The currency code is the same as that in the ClickConversion message. |
| 62 | + 'items' => $items, |
| 63 | + ]; |
| 64 | + } |
| 65 | + |
| 66 | + private static function getItems(OrderInterface $order): array |
| 67 | + { |
| 68 | + $items = []; |
| 69 | + |
| 70 | + foreach ($order->getItems() as $item) { |
| 71 | + $productId = $item->getVariant()?->getCode(); |
| 72 | + if (null === $productId) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + $items[] = [ |
| 77 | + 'product_id' => $productId, |
| 78 | + 'quantity' => $item->getQuantity(), |
| 79 | + 'unit_price' => round($item->getUnitPrice() / 100, 2), |
| 80 | + ]; |
| 81 | + } |
| 82 | + |
| 83 | + return $items; |
| 84 | + } |
| 85 | +} |
0 commit comments