-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathAddShippingInfoSubscriber.php
More file actions
70 lines (57 loc) · 2.33 KB
/
AddShippingInfoSubscriber.php
File metadata and controls
70 lines (57 loc) · 2.33 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
<?php
declare(strict_types=1);
namespace Setono\SyliusAnalyticsPlugin\EventSubscriber;
use Psr\EventDispatcher\EventDispatcherInterface;
use Setono\GoogleAnalyticsBundle\Event\ClientSideEvent;
use Setono\GoogleAnalyticsEvents\Event\AddShippingInfoEvent;
use Setono\SyliusAnalyticsPlugin\Resolver\Items\ItemsResolverInterface;
use Setono\SyliusAnalyticsPlugin\Util\FormatAmountTrait;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
use Sylius\Component\Core\Model\OrderInterface;
use Webmozart\Assert\Assert;
final class AddShippingInfoSubscriber extends AbstractEventSubscriber
{
use FormatAmountTrait;
private EventDispatcherInterface $eventDispatcher;
private ItemsResolverInterface $itemsResolver;
public function __construct(EventDispatcherInterface $eventDispatcher, ItemsResolverInterface $itemsResolver)
{
parent::__construct();
$this->eventDispatcher = $eventDispatcher;
$this->itemsResolver = $itemsResolver;
}
public static function getSubscribedEvents(): array
{
return [
'sylius.order.post_select_shipping' => 'track',
];
}
public function track(ResourceControllerEvent $resourceControllerEvent): void
{
try {
/** @var OrderInterface|mixed $order */
$order = $resourceControllerEvent->getSubject();
Assert::isInstanceOf($order, OrderInterface::class);
$shippingMethodCode = null;
foreach ($order->getShipments() as $shipment) {
$shippingMethod = $shipment->getMethod();
if (null === $shippingMethod) {
continue;
}
$shippingMethodCode = $shippingMethod->getCode();
}
Assert::notNull($shippingMethodCode);
$this->eventDispatcher->dispatch(
new ClientSideEvent(
AddShippingInfoEvent::create()
->setValue(self::formatAmount($order->getTotal()))
->setCurrency($order->getCurrencyCode())
->setShippingTier($shippingMethodCode)
->setItems($this->itemsResolver->resolveFromOrder($order)),
),
);
} catch (\Throwable $e) {
$this->log(AddShippingInfoEvent::getName(), $e);
}
}
}