-
Notifications
You must be signed in to change notification settings - Fork 17
/
ViewCategorySubscriber.php
109 lines (87 loc) · 2.94 KB
/
ViewCategorySubscriber.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
namespace Setono\SyliusFacebookPlugin\EventSubscriber;
use Psr\EventDispatcher\EventDispatcherInterface;
use Setono\SyliusFacebookPlugin\Event\CategoryViewedEvent;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
use Sylius\Bundle\ResourceBundle\Grid\View\ResourceGridView;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Taxonomy\Model\TaxonInterface;
use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;
use Traversable;
/**
* See https://developers.facebook.com/docs/marketing-api/audiences/guides/dynamic-product-audiences/#setuppixel
* for reference of the 'ViewCategory' custom event
*/
final class ViewCategorySubscriber extends EventSubscriber
{
private LocaleContextInterface $localeContext;
private TaxonRepositoryInterface $taxonRepository;
public function __construct(
EventDispatcherInterface $eventDispatcher,
LocaleContextInterface $localeContext,
TaxonRepositoryInterface $taxonRepository
) {
parent::__construct($eventDispatcher);
$this->localeContext = $localeContext;
$this->taxonRepository = $taxonRepository;
}
public static function getSubscribedEvents(): array
{
return [
'sylius.product.index' => 'track',
];
}
protected function callback(): callable
{
return function (ResourceControllerEvent $event): ?CategoryViewedEvent {
$gridView = $event->getSubject();
if (!$gridView instanceof ResourceGridView) {
return null;
}
$taxon = $this->getTaxon($gridView);
if (null === $taxon) {
return null;
}
return new CategoryViewedEvent($taxon, $this->getProducts($gridView));
};
}
/**
* @return list<string>
*/
private function getProducts(ResourceGridView $gridView): array
{
$data = $gridView->getData();
if (!$data instanceof Traversable) {
return [];
}
$codes = [];
$i = 0;
$max = 10;
/** @var mixed $datum */
foreach ($data as $datum) {
if ($i >= $max) {
break;
}
if ($datum instanceof ProductInterface) {
$code = $datum->getCode();
if (null !== $code) {
$codes[] = $code;
}
}
++$i;
}
return $codes;
}
private function getTaxon(ResourceGridView $gridView): ?TaxonInterface
{
$request = $gridView->getRequestConfiguration()->getRequest();
$slug = $request->attributes->get('slug');
if (!is_string($slug)) {
return null;
}
$locale = $this->localeContext->getLocaleCode();
return $this->taxonRepository->findOneBySlug($slug, $locale);
}
}