-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathPurchaseSubscriber.php
77 lines (61 loc) · 2.05 KB
/
PurchaseSubscriber.php
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
<?php
declare(strict_types=1);
namespace Setono\SyliusFacebookPlugin\EventSubscriber;
use Psr\EventDispatcher\EventDispatcherInterface;
use Setono\SyliusFacebookPlugin\Event\OrderPlacedEvent;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Order\Repository\OrderRepositoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class PurchaseSubscriber extends EventSubscriber
{
private OrderRepositoryInterface $orderRepository;
public function __construct(
EventDispatcherInterface $eventDispatcher,
OrderRepositoryInterface $orderRepository
) {
parent::__construct($eventDispatcher);
$this->orderRepository = $orderRepository;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'track',
];
}
protected function callback(): callable
{
return function (RequestEvent $event): ?OrderPlacedEvent {
if (!$event->isMainRequest()) {
return null;
}
$request = $event->getRequest();
if ($request->attributes->get('_route') !== 'sylius_shop_order_thank_you') {
return null;
}
$order = $this->resolveOrder($request);
if (null === $order) {
return null;
}
return new OrderPlacedEvent($order);
};
}
/**
* This method will return an OrderInterface if
* - A session exists with the order id
* - The order can be found in the order repository
*/
private function resolveOrder(Request $request): ?OrderInterface
{
$orderId = $request->getSession()->get('sylius_order_id');
if (!is_scalar($orderId)) {
return null;
}
$order = $this->orderRepository->find($orderId);
if (!$order instanceof OrderInterface) {
return null;
}
return $order;
}
}