-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathPurchaseSubscriber.php
More file actions
93 lines (76 loc) · 3.01 KB
/
Copy pathPurchaseSubscriber.php
File metadata and controls
93 lines (76 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
declare(strict_types=1);
namespace Setono\SyliusAnalyticsPlugin\EventSubscriber;
use Psr\EventDispatcher\EventDispatcherInterface;
use Setono\GoogleAnalyticsBundle\Event\ClientSideEvent;
use Setono\GoogleAnalyticsEvents\Event\PurchaseEvent;
use Setono\SyliusAnalyticsPlugin\Resolver\Items\ItemsResolverInterface;
use Setono\SyliusAnalyticsPlugin\Util\FormatAmountTrait;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Order\Repository\OrderRepositoryInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Webmozart\Assert\Assert;
final class PurchaseSubscriber extends AbstractEventSubscriber
{
use FormatAmountTrait;
private EventDispatcherInterface $eventDispatcher;
private OrderRepositoryInterface $orderRepository;
private ItemsResolverInterface $itemsResolver;
public function __construct(
EventDispatcherInterface $eventDispatcher,
OrderRepositoryInterface $orderRepository,
ItemsResolverInterface $itemsResolver
) {
parent::__construct();
$this->eventDispatcher = $eventDispatcher;
$this->orderRepository = $orderRepository;
$this->itemsResolver = $itemsResolver;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'track',
];
}
public function track(RequestEvent $requestEvent): void
{
try {
if (!$requestEvent->isMainRequest()) {
return;
}
$request = $requestEvent->getRequest();
$route = $request->attributes->get('_route');
if ('sylius_shop_order_thank_you' !== $route) {
return;
}
$orderId = $request->getSession()->get('sylius_order_id');
if (!is_scalar($orderId)) {
return;
}
$order = $this->orderRepository->find($orderId);
if (!$order instanceof OrderInterface) {
return;
}
$channel = $order->getChannel();
Assert::notNull($channel);
$this->eventDispatcher->dispatch(
new ClientSideEvent(
PurchaseEvent::create((string) $order->getNumber())
->setAffiliation(sprintf(
'%s (%s)',
(string) $channel->getName(),
(string) $order->getLocaleCode(),
))
->setValue(self::formatAmount($order->getTotal()))
->setCurrency($order->getCurrencyCode())
->setTax(self::formatAmount($order->getTaxTotal()))
->setShipping(self::formatAmount($order->getShippingTotal()))
->setItems($this->itemsResolver->resolveFromOrder($order)),
),
);
} catch (\Throwable $e) {
$this->log(PurchaseEvent::getName(), $e);
}
}
}